Skip to content

Instantly share code, notes, and snippets.

@hariscs
Created February 25, 2024 17:48
Show Gist options
  • Save hariscs/7cc6374a4080922b74e143aa735e5b62 to your computer and use it in GitHub Desktop.
Save hariscs/7cc6374a4080922b74e143aa735e5b62 to your computer and use it in GitHub Desktop.
Schema Validation Using Zod
import { Request, Response, NextFunction } from 'express'
import { z } from 'zod'
export function validate_schema(schema: z.AnyZodObject) {
return (req: Request, res: Response, next: NextFunction) => {
try {
schema.parse(req.body)
next()
} catch (error) {
if (error instanceof z.ZodError) {
const error_messages = error.errors.map((issue) => ({
message: `${issue.path.join('.')} - ${issue.message}`,
}))
res.status(400).json({ error: 'Invalid data', error_messages })
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment