Skip to content

Commit

Permalink
refactor: client initializer functions can also be non-Promises
Browse files Browse the repository at this point in the history
  • Loading branch information
TheEdoRan committed Oct 1, 2023
1 parent d80eec4 commit 9b9c8f6
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 13 deletions.
7 changes: 5 additions & 2 deletions packages/example-app/src/lib/safe-action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,20 @@ export const action = createSafeActionClient({
// You can provide a custom log Promise, otherwise the lib will use `console.error`
// as the default logging system. If you want to disable server errors logging,
// just pass an empty Promise.
handleServerErrorLog: async (e) => {
handleServerErrorLog: (e) => {
console.error("CUSTOM ERROR LOG FUNCTION:", e);
},
});

export const authAction = createSafeActionClient({
// You can provide a context builder function. In this case, context is used
// for (fake) auth purposes.
buildContext: async () => {
buildContext: () => {
return {
userId: randomUUID(),
};
},
middleware(ctx) {
console.log("HELLO FROM ACTION MIDDLEWARE, USER ID:", ctx.userId);
},
});
22 changes: 11 additions & 11 deletions packages/next-safe-action/src/server.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { z } from "zod";
import type { SafeAction, ServerCode } from "./types";
import type { MaybePromise, SafeAction, ServerCode } from "./types";
import { DEFAULT_SERVER_ERROR, isError, isNextNotFoundError, isNextRedirectError } from "./utils";

/**
Expand All @@ -10,24 +10,24 @@ import { DEFAULT_SERVER_ERROR, isError, isNextNotFoundError, isNextRedirectError
* {@link https://github.com/TheEdoRan/next-safe-action/tree/main/packages/next-safe-action#project-configuration See an example}
*/
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>;
buildContext?: () => MaybePromise<Context>;
handleServerErrorLog?: (e: Error) => MaybePromise<void>;
handleReturnedServerError?: (e: Error) => MaybePromise<{ serverError: string }>;
middleware?: (ctx: Context) => MaybePromise<void>;
}) => {
// If server log function is not provided, default to `console.error` for logging
// server error messages.
const handleServerErrorLog =
createOpts?.handleServerErrorLog ||
(async (e) => {
((e) => {
console.error("Action error:", (e as Error).message);
});

// If `handleReturnedServerError` is provided, use it to handle server error
// messages returned on the client.
// Otherwise mask the error and use a generic message.
const handleReturnedServerError =
createOpts?.handleReturnedServerError || (async () => ({ serverError: DEFAULT_SERVER_ERROR }));
createOpts?.handleReturnedServerError || (() => ({ serverError: DEFAULT_SERVER_ERROR }));

// `actionBuilder` is the server function that creates a new action.
// It expects an input schema and a `serverCode` function, so the action
Expand Down Expand Up @@ -56,10 +56,10 @@ export const createSafeActionClient = <Context extends object>(createOpts?: {

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

// Execute middleware code, if Promise is provided.
await createOpts?.middleware?.(ctx);
await Promise.resolve(createOpts?.middleware?.(ctx));

return { data: await serverCode(parsedInput.data, ctx) };
} catch (e: unknown) {
Expand All @@ -75,9 +75,9 @@ export const createSafeActionClient = <Context extends object>(createOpts?: {
return { serverError: DEFAULT_SERVER_ERROR };
}

await handleServerErrorLog(e as Error);
await Promise.resolve(handleServerErrorLog(e as Error));

return await handleReturnedServerError(e as Error);
return await Promise.resolve(handleReturnedServerError(e as Error));
}
};
};
Expand Down

0 comments on commit 9b9c8f6

Please sign in to comment.