Skip to content

Instantly share code, notes, and snippets.

@lithdew
Created July 12, 2023 20:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lithdew/0fc078de90e03f344476b1daabe5943f to your computer and use it in GitHub Desktop.
Save lithdew/0fc078de90e03f344476b1daabe5943f to your computer and use it in GitHub Desktop.
react server action zod validation
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