Skip to content

Commit

Permalink
feat: add action middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
TheEdoRan committed Sep 27, 2023
1 parent f48b524 commit 6111ff4
Showing 1 changed file with 6 additions and 2 deletions.
8 changes: 6 additions & 2 deletions packages/next-safe-action/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export const createSafeActionClient = <Context extends object>(createOpts?: {
buildContext?: () => Promise<Context>;
handleReturnedServerError?: (e: Error) => Promise<{ serverError: string }>;
handleServerErrorLog?: (e: Error) => Promise<void>;
middleware?: (ctx: Context) => Promise<void>;
}) => {
// If server log function is not provided, default to `console.error` for logging
// server error messages.
Expand Down Expand Up @@ -55,9 +56,12 @@ export const createSafeActionClient = <Context extends object>(createOpts?: {

// Get the context if `buildContext` is provided, otherwise use an
// empty object.
const ctx = (await createOpts?.buildContext?.()) ?? {};
const ctx = ((await createOpts?.buildContext?.()) ?? {}) as Context;

return { data: await serverCode(parsedInput.data, ctx as Context) };
// Execute middleware code, if Promise is provided.
await createOpts?.middleware?.(ctx);

return { data: await serverCode(parsedInput.data, ctx) };
} catch (e: unknown) {
// next/navigation functions work by throwing an error that will be
// processed internally by Next.js. So, in this case we need to rethrow it.
Expand Down

0 comments on commit 6111ff4

Please sign in to comment.