22 lines
617 B
TypeScript
22 lines
617 B
TypeScript
import { Request, Response, NextFunction } from 'express';
|
|
import { ZodSchema, ZodError } from 'zod';
|
|
|
|
export function validate(schema: ZodSchema) {
|
|
return (req: Request, res: Response, next: NextFunction): void => {
|
|
try {
|
|
schema.parse(req.body);
|
|
next();
|
|
} catch (err) {
|
|
if (err instanceof ZodError) {
|
|
const errors = err.errors.map(e => ({
|
|
field: e.path.join('.'),
|
|
message: e.message,
|
|
}));
|
|
res.status(400).json({ success: false, error: 'Ошибка валидации', details: errors });
|
|
return;
|
|
}
|
|
next(err);
|
|
}
|
|
};
|
|
}
|