zerot
    Preparing search index...

    Function createServerAction

    • Helper to integrate Next.js Server Actions with the contract system. This function acts as a wrapper for Server Actions, handling contract violations appropriately. It extracts input from FormData (if applicable), retrieves the authentication context, executes the action, and catches ContractViolationError to return a structured response or redirect.

      Type Parameters

      • TInput

        The expected type of the input for the server action.

      • TOutput

        The expected return type of the server action.

      Parameters

      • actionFn: (input: TInput, context: any) => TOutput | Promise<TOutput>

        The original server action function that takes input and context.

      Returns (formData: TInput | FormData) => Promise<any>

      A wrapped server action function that can be used directly in Next.js.

      // app/actions.ts (Server Component)
      "use server";

      import { createServerAction } from "../../src/integrations/server-actions";
      import { contract } from "../../src/core/contract";
      import { auth } from "../../src/conditions/auth";
      import { z } from "zod";
      import { validates } from "../../src/conditions/validation";

      const CreatePostSchema = z.object({
      title: z.string().min(1),
      content: z.string().min(10),
      });

      class PostActions {
      @contract({
      requires: [auth("user"), validates(CreatePostSchema)],
      })
      async createPost(input: z.infer<typeof CreatePostSchema>, context: any) {
      console.log("Creating post:", input, "by user:", context.user?.id);
      // Logic to save post to DB
      return { postId: "new-post-id", ...input };
      }
      }

      export const createPostAction = createServerAction(new PostActions().createPost);