Created
July 21, 2023 17:59
-
-
Save gustavomorinaga/0b0c590d8b3c7c9e6f09692425dfef24 to your computer and use it in GitHub Desktop.
Best way to parse and validate data with Zod in any context.
This file contains hidden or 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 { AnyZodObject, ZodError, z } from 'zod'; | |
| import { fromZodError } from 'zod-validation-error'; | |
| export async function zParse<T extends AnyZodObject>( | |
| schema: T, | |
| data: any | |
| ): Promise<z.infer<T>> { | |
| try { | |
| return await schema.parseAsync(data); | |
| } catch (error) { | |
| throw fromZodError(error as ZodError); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment