Created
February 25, 2024 17:48
-
-
Save hariscs/7cc6374a4080922b74e143aa735e5b62 to your computer and use it in GitHub Desktop.
Schema Validation Using Zod
This file contains 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 { 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