Skip to content

Commit

Permalink
feat: move context under utils
Browse files Browse the repository at this point in the history
  • Loading branch information
theboxer committed Jan 31, 2024
1 parent 1386ad0 commit 5b750a8
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 11 deletions.
10 changes: 7 additions & 3 deletions packages/example-app/src/app/login-action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@ const input = z.object({
password: z.string().min(8).max(100),
});

export const loginUser = action(input, async ({ username, password }, _ctx, { returnValidationErrors }) => {
export const loginUser = action(input, async ({ username, password }, { returnValidationErrors, ctx }) => {
if (username === "johndoe") {
returnValidationErrors({
username: ['user_suspended'],
username: {
_errors: ['user_suspended']
},
});
}

Expand All @@ -22,6 +24,8 @@ export const loginUser = action(input, async ({ username, password }, _ctx, { re
}

returnValidationErrors({
username: ['incorrect_credentials'],
username: {
_errors: ['incorrect_credentials']
},
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export const editUser = authAction(
// Here you have access to `userId`, which comes from `buildContext`
// return object in src/lib/safe-action.ts.
// \\\\\
async ({ fullName, age }, userId) => {
async ({ fullName, age }, { ctx: { userId } }) => {
if (fullName.toLowerCase() === "john doe") {
return {
error: {
Expand Down
2 changes: 2 additions & 0 deletions packages/example-app/src/lib/safe-action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ export const authAction = createSafeActionClient({
"PARSED INPUT:",
parsedInput
);

return { userId };
},
handleReturnedServerError,
});
15 changes: 8 additions & 7 deletions packages/next-safe-action/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ export type SafeAction<S extends Schema, Data> = (input: InferIn<S>) => Promise<
validationErrors?: ValidationErrors<S>;
}>;

type Utils<S extends Schema> = {
type Utils<S extends Schema, Context> = {
ctx: Context
returnValidationErrors: typeof throwServerValidationError<S>
};

Expand All @@ -35,8 +36,7 @@ type Utils<S extends Schema> = {
*/
export type ServerCodeFn<S extends Schema, Data, Context> = (
parsedInput: Infer<S>,
ctx: Context,
utils: Utils<S>,
utils: Utils<S, Context>,
) => Promise<Data>;

// UTILS
Expand All @@ -60,7 +60,7 @@ export class ServerValidationError<S extends Schema> extends Error {
*
* {@link https://next-safe-action.dev/docs/getting-started See an example}
*/
export const createSafeActionClient = <Context>(createOpts?: SafeClientOpts<Context>) => {
export const createSafeActionClient = <Context = null>(createOpts?: SafeClientOpts<Context>) => {
// If server log function is not provided, default to `console.error` for logging
// server error messages.
const handleServerErrorLog =
Expand All @@ -85,8 +85,9 @@ export const createSafeActionClient = <Context>(createOpts?: SafeClientOpts<Cont
): SafeAction<S, Data> => {
// Helper function to create ServerValidationError with injected schema

const utils: Utils<S> = {
const utils: Utils<S, Context> = {
returnValidationErrors: throwServerValidationError,
ctx: null as Context,
};

// This is the function called by client. If `input` fails the schema
Expand All @@ -104,11 +105,11 @@ export const createSafeActionClient = <Context>(createOpts?: SafeClientOpts<Cont
}

// Get the context if `middleware` is provided.
const ctx = (await Promise.resolve(createOpts?.middleware?.(parsedInput.data))) as Context;
utils.ctx = (await Promise.resolve(createOpts?.middleware?.(parsedInput.data))) as Context;

// Get `result.data` from the server code function. If it doesn't return
// anything, `data` will be `null`.
const data = ((await serverCode(parsedInput.data, ctx, utils)) ?? null) as Data;
const data = ((await serverCode(parsedInput.data, utils)) ?? null) as Data;

return { data };
} catch (e: unknown) {
Expand Down

0 comments on commit 5b750a8

Please sign in to comment.