Last active
January 15, 2024 20:06
-
-
Save bryanjhv/0b3f5dcf213bf2f2f6f5d4b75480354e to your computer and use it in GitHub Desktop.
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 type { FastifyInstance } from 'fastify' | |
import fp from 'fastify-plugin' | |
import type { ZodAny, ZodError, ZodTypeAny } from 'zod' | |
import { z } from 'zod' | |
import { fromZodError } from 'zod-validation-error' | |
declare module 'fastify' { | |
// TODO: Copy ZodTypeProvider here (output) | |
interface FastifyTypeProviderDefault { | |
output: this['input'] extends ZodTypeAny ? z.infer<this['input']> : unknown | |
} | |
} | |
function asError(zodError: ZodError) { | |
return fromZodError(zodError, { prefix: null, issueSeparator: '\n' }) | |
} | |
async function plugin(server: FastifyInstance) { | |
server.setValidatorCompiler<ZodAny>(({ schema }) => data => { | |
const result = schema.safeParse(data) | |
if (result.success) return { value: result.data } | |
return { error: asError(result.error) } | |
}) | |
server.setSerializerCompiler<ZodAny>(({ schema }) => data => { | |
const result = schema.safeParse(data) | |
if (result.success) return JSON.stringify(result.data) | |
throw asError(result.error) | |
}) | |
} | |
export default fp(plugin) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment