validate-request.ts55 lines, 1.4 KB
| 1 | import { z } from "zod"; |
| 2 | import { HttpError } from "../errors/http-error"; |
| 3 | |
| 4 | import type { NextFunction, Request, Response } from "express"; |
| 5 | import { AnyZodObject, ZodError, ZodTypeAny } from "zod"; |
| 6 | |
| 7 | type Schema = AnyZodObject | ZodTypeAny; |
| 8 | type ParamsRecord = Record<string, string>; |
| 9 | type QueryRecord = Record<string, unknown>; |
| 10 | |
| 11 | export interface RequestValidationSchemas { |
| 12 | body?: Schema; |
| 13 | params?: Schema; |
| 14 | query?: Schema; |
| 15 | } |
| 16 | |
| 17 | const formatedError = (error: ZodError) => |
| 18 | error.errors.map((issue) => ({ |
| 19 | path: issue.path.join("."), |
| 20 | message: issue.message, |
| 21 | })); |
| 22 | |
| 23 | export const validateRequest = (schemas: RequestValidationSchemas) => { |
| 24 | return (req: Request, _res: Response, next: NextFunction) => { |
| 25 | try { |
| 26 | if (schemas.body) { |
| 27 | const parsedBody = schemas.body.parse(req.body) as unknown; |
| 28 | req.body = parsedBody; |
| 29 | } |
| 30 | |
| 31 | if (schemas.params) { |
| 32 | const parsedParams = schemas.params.parse(req.params) as ParamsRecord; |
| 33 | req.params = parsedParams as Request["params"]; |
| 34 | } |
| 35 | |
| 36 | if (schemas.query) { |
| 37 | const parsedQuery = schemas.query.parse(req.query) as QueryRecord; |
| 38 | req.query = parsedQuery as Request["query"]; |
| 39 | } |
| 40 | |
| 41 | next(); |
| 42 | } catch (error) { |
| 43 | if (error instanceof ZodError) { |
| 44 | next( |
| 45 | new HttpError(422, "Validation Error", { |
| 46 | issues: formatedError(error), |
| 47 | }), |
| 48 | ); |
| 49 | return; |
| 50 | } |
| 51 | |
| 52 | next(error); |
| 53 | } |
| 54 | }; |
| 55 | }; |