Skip to content

Instantly share code, notes, and snippets.

@audunolsen
Created November 28, 2022 11:26
Show Gist options
  • Save audunolsen/47371e79dc67f44b0e481d1aa8145008 to your computer and use it in GitHub Desktop.
Save audunolsen/47371e79dc67f44b0e481d1aa8145008 to your computer and use it in GitHub Desktop.
Just an idea for utilizing zod in a generic manner
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