Drizzle-zod for validation - part1

This commit is contained in:
Justin xzHome
2025-07-06 22:38:21 +09:00
parent 4f0646dd2a
commit 4f35ed1abd
4 changed files with 59 additions and 4 deletions

View File

@@ -0,0 +1,20 @@
import { Request, Response, NextFunction } from 'express';
import { z, ZodError } from 'zod';
export function validateData(schema: z.ZodObject<any, any>) {
return (req: Request, res: Response, next: NextFunction) => {
try {
schema.parse(req.body);
next();
} catch (error) {
if (error instanceof ZodError) {
const errorMessages = error.errors.map((issue: any) => ({
message: `${issue.path.join('.')} is ${issue.message}`,
}));
res.status(400).json({ error: 'Invalid data', details: errorMessages });
} else {
res.status(500).json({ error: 'Internal Server Error' });
}
}
};
}