1 import { NextFunction, Request, RequestHandler, Response } from "express"
2
3 type handler = (req: Request, res: Response) => Promise<void>
4
5 export const wrapHandler = (fn: handler): RequestHandler => {
6 return async (req: Request, res: Response, next: NextFunction) => {
7 const req_ = req as Request & { errors?: Error[] }
8 if (req_?.errors?.length) {
9 return res.status(400).json({
10 errors: req_.errors,
11 message:
12 "Provided request body contains errors. Please check the data and retry the request",
13 })
14 }
15
16 try {
17 return await fn(req, res)
18 } catch (err) {
19 next(err)
20 }
21 }
22 }
23
24 /**
25 * @schema MultipleErrors
26 * title: "Multiple Errors"
27 * type: object
28 * properties:
29 * errors:
30 * type: array
31 * description: Array of errors
32 * items:
33 * $ref: "#/components/schemas/Error"
34 * message:
35 * type: string
36 * default: "Provided request body contains errors. Please check the data and retry the request"
37 */