Created
November 28, 2022 11:26
-
-
Save audunolsen/47371e79dc67f44b0e481d1aa8145008 to your computer and use it in GitHub Desktop.
Just an idea for utilizing zod in a generic manner
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 * as z from 'zod' | |
import { Schema } from 'zod' | |
export async function parse<T extends Schema>( | |
schema: T | ((zod: typeof z) => T), | |
) { | |
const codec = schema instanceof Schema ? schema : schema(z) | |
return async function (input: Response) { | |
const json = await input.json() | |
const result: z.infer<T> | z.ZodError<T> = await codec | |
.parseAsync(json) | |
.catch(e => e) | |
return result | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment