| 1 | import { Request, Response, NextFunction } from "express"; |
| 2 | import { validationResult } from "express-validator"; |
| 3 | import { StatusCodes } from "http-status-codes"; |
| 4 | import { errorResponse } from "../utils/response"; |
| 5 | |
| 6 | export const validateRequest = ( |
| 7 | req: Request, |
| 8 | res: Response, |
| 9 | next: NextFunction |
| 10 | ): void => { |
| 11 | const errors = validationResult(req); |
| 12 | if (!errors.isEmpty()) { |
| 13 | const formattedErrors = errors.array().map((err) => ({ |
| 14 | path: err.type === "field" ? err.path : err.type, |
| 15 | msg: err.msg, |
| 16 | })); |
| 17 | |
| 18 | // Create a more descriptive message that includes the first error |
| 19 | const firstError = formattedErrors[0]; |
| 20 | const detailedMessage = `Validation failed: ${firstError.msg} ${ |
| 21 | firstError.path ? `for '${firstError.path}'` : "" |
| 22 | }${ |
| 23 | formattedErrors.length > 1 |
| 24 | ? ` (and ${formattedErrors.length - 1} more errors)` |
| 25 | : "" |
| 26 | }`; |
| 27 | |
| 28 | // Always include validation errors even in production |
| 29 | res.status(StatusCodes.BAD_REQUEST).json({ |
| 30 | status: "error", |
| 31 | message: detailedMessage, |
| 32 | errors: formattedErrors, |
| 33 | }); |
| 34 | return; |
| 35 | } |
| 36 | next(); |
| 37 | }; |