-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmakeServerAction.ts
More file actions
39 lines (35 loc) · 1.04 KB
/
makeServerAction.ts
File metadata and controls
39 lines (35 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import { ZodSchema } from "zod";
import {
createSafeActionClient,
DEFAULT_SERVER_ERROR_MESSAGE,
} from "next-safe-action";
import { Exception } from "@/lib/exception/Exception";
/**
* Provides a server action ready to use in `useFormServerAction` (`src/lib/browser/useFormServerAction.tsx`)
*
* @param inputSchema a Zod form schema.
* @param handler a server action that expects data of the same schema.
*
* @returns a type-safe action.
*/
export function makeServerAction<Input, ReturnValue>(
inputSchema: ZodSchema<Input>,
handler: (input: Input) => Promise<ReturnValue>
) {
return createSafeActionClient({
handleServerError(error) {
const isException = error instanceof Exception;
console.error(
`${isException ? "⚠️ Action exception" : "❌ Action error"}: ${
error.message
}`
);
if (isException) {
return error.message;
}
return DEFAULT_SERVER_ERROR_MESSAGE;
},
})
.schema(inputSchema)
.action(async ({ parsedInput }) => handler(parsedInput));
}