Next.js Discord

Discord Forum

Question about server action handler

Unanswered
American black bear posted this in #help-forum
Open in Discord
American black bearOP
i've a simple code to handle server action, but i want to ask if this code is ok? it's work's as well, but idk if this running right on production

class Action {
  private baseSchema?: ZodSchema;
  private middlewareFns: (({
    next,
  }: {
    next: ({ ctx }: { ctx?: any }) => Action | void;
  }) => Promise<Action>)[] = [];
  private debug: boolean;

  constructor(options: { debug?: boolean }) {
    this.debug =
      options.debug || process.env.NODE_ENV === "development" || false;
    if (this.debug) {
      console.log("Server action initialized");
    }
  }

  action<I, R>(actionFn: ServerAction<I, R>) {
    return async (input: I): Promise<ServerActionResponse<R>> => {
      try {
        let context = {} as any;
        for (const middlewareFn of this.middlewareFns) {
          await middlewareFn({
            next: ({ ctx }) => {
              if (this.debug) {
                console.log("Middleware executed, context:", ctx);
              }
              context = { ...context, ...ctx };
            },
          });
        }

        if (this.baseSchema) {
          if (this.debug) {
            console.log("Validating input with schema:", this.baseSchema);
          }
          const validatedInput = this.baseSchema.safeParse(input);
          if (!validatedInput.success) {
            throw new ServerActionError(validatedInput.error.errors[0].message);
          }
          input = validatedInput.data;
        }

        const result = await actionFn({ input, ctx: context });
        if (this.debug) {
          console.log("Server action result:", result);
        }
        return { data: result };
      } catch (error: any) {
        // error handling
      }
    };
  }

  use(
    middlewareFn: ({
      next,
    }: {
      next: ({ ctx }: { ctx?: any }) => Action;
    }) => Promise<Action>
  ) {
    this.middlewareFns.push(middlewareFn as any);
    return this;
  }
}

export const serverAction = new Action({ debug: true });

0 Replies