Created
April 8, 2024 17:30
-
-
Save JTRNS/f5c54fdc8fdeffb485bafae582bc8d77 to your computer and use it in GitHub Desktop.
Zod FormData Helper
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"; | |
type ParsedFormData<T extends z.AnyZodObject> = { | |
data: null; | |
errors: z.typeToFlattenedError<z.infer<T>>['fieldErrors'] | |
} | { | |
data: z.infer<T>; | |
errors: null; | |
} | |
export async function parseFormData< | |
Schema extends z.AnyZodObject | |
>(schema: Schema, request: Request,): Promise<ParsedFormData<Schema>> { | |
const formdata = await request.formData(); | |
const obj = Object.fromEntries(formdata); | |
const result = await schema.safeParseAsync(obj); | |
return result.success | |
? { data: result.data, errors: null } | |
: { data: null, errors: result.error.flatten().fieldErrors }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment