Skip to content

Instantly share code, notes, and snippets.

@bryanjhv
Last active January 15, 2024 20:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bryanjhv/0b3f5dcf213bf2f2f6f5d4b75480354e to your computer and use it in GitHub Desktop.
Save bryanjhv/0b3f5dcf213bf2f2f6f5d4b75480354e to your computer and use it in GitHub Desktop.
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