Created
July 12, 2023 20:25
-
-
Save lithdew/0fc078de90e03f344476b1daabe5943f to your computer and use it in GitHub Desktop.
react server action zod validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { z } from "zod"; | |
import { fromZodError } from "zod-validation-error"; | |
export function procedure<TSchema extends z.ZodTypeAny = z.ZodNever>(inputSchema?: TSchema) { | |
type InputArgs = TSchema extends z.ZodNever ? [] : [z.output<TSchema>] | |
type TransformedArgs = TSchema extends z.ZodNever ? [] : [z.input<TSchema>] | |
return { | |
// eslint-disable-next-line no-unused-vars | |
do<TOutput>(fn: (...input: InputArgs) => TOutput) { | |
return (...input: TransformedArgs) => { | |
if (inputSchema) { | |
const result = inputSchema.safeParse(input[0]) | |
if (!result.success) { | |
throw fromZodError(result.error) | |
} | |
return fn(...[result.data] as InputArgs) | |
} | |
return fn(...[input[0]] as InputArgs) | |
} | |
} | |
} | |
} | |
export function paginationSchema<TCursor extends z.ZodTypeAny = z.ZodNever>(cursorSchema: TCursor) { | |
return z.object({ | |
before: cursorSchema, | |
after: cursorSchema, | |
}).partial(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment