18 lines
803 B
TypeScript
18 lines
803 B
TypeScript
import type { z, ZodType } from 'zod'
|
|
|
|
// `createServerFn().validator(schema)` passes a zod schema straight through to
|
|
// TanStack Start, which on failure throws `new Error(JSON.stringify(issues))` —
|
|
// the raw issue array, not a message meant for a user to read. Wrapping the
|
|
// schema in a plain function (`.validator(zodValidator(schema))`) routes
|
|
// validation through this instead, so a rejected field surfaces its own zod
|
|
// `.message` (e.g. "Enter a valid phone number") rather than a JSON blob.
|
|
export function zodValidator<Schema extends ZodType>(schema: Schema) {
|
|
return (input: unknown): z.infer<Schema> => {
|
|
const result = schema.safeParse(input)
|
|
if (!result.success) {
|
|
throw new Error(result.error.issues[0]?.message ?? 'Invalid input')
|
|
}
|
|
return result.data
|
|
}
|
|
}
|