| import { Request, Response, NextFunction } from 'express'; | |
| import { ZodSchema, ZodError } from 'zod'; | |
| interface ValidateOptions { | |
| body?: ZodSchema<any>; | |
| query?: ZodSchema<any>; | |
| params?: ZodSchema<any>; | |
| } | |
| export function Validate(schemas: ValidateOptions): MethodDecorator { | |
| return function ( | |
| target: any, | |
| propertyKey: string | symbol, | |
| descriptor: PropertyDescriptor | |
| ) { | |
| const originalMethod = descriptor.value; | |
| descriptor.value = async function ( | |
| req: Request, | |
| res: Response, | |
| next: NextFunction | |
| ) { | |
| try { | |
| if (schemas.body) { | |
| req.body = schemas.body.parse(req.body); | |
| } | |
| if (schemas.query) { | |
| req.query = schemas.query.parse(req.query); | |
| } | |
| if (schemas.params) { | |
| req.params = schemas.params.parse(req.params); | |
| } | |
| return await originalMethod.call(this, req, res, next); | |
| } catch (err: any) { | |
| if (err instanceof ZodError) { | |
| const formattedErrors = err.issues.map(issue => ({ | |
| field: issue.path.join('.'), | |
| error: issue.message | |
| })); | |
| return res.error(400, 'VALIDATION_ERROR', 'Failed to validate data', formattedErrors); | |
| } | |
| return res.error(500, 'INTERNAL_SERVER_ERROR', 'An unexpected error occurred'); | |
| } | |
| }; | |
| return descriptor; | |
| }; | |
| } | |