All files / server/src/middleware validateRequest.ts

100% Statements 18/18
100% Branches 4/4
100% Functions 4/4
100% Lines 18/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44        42x 839x   2877x 2877x 25x         25x 25x   2852x 2852x     42x 79x   65x 65x 2x         2x 2x       63x         63x    
import { NextFunction, Request, Response } from "express";
import { z } from "zod";
import { logger } from "server/utils/logger";
 
export const validateBody =
  (schema: z.ZodType) =>
  (req: Request, res: Response, next: NextFunction): void => {
    const result = schema.safeParse(req.body);
    if (!result.success) {
      logger.error(
        new Error(`Error validating ${req.method} ${req.path} body`, {
          cause: result.error,
        }),
      );
      res.sendStatus(422);
      return;
    }
    req.body = result.data;
    next();
  };
 
export const validateQuery =
  (schema: z.ZodType) =>
  (req: Request, res: Response, next: NextFunction): void => {
    const result = schema.safeParse(req.query);
    if (!result.success) {
      logger.error(
        new Error(`Error validating ${req.method} ${req.path} query`, {
          cause: result.error,
        }),
      );
      res.sendStatus(422);
      return;
    }
    // Express 5 makes req.query a getter, so direct assignment is unsafe;
    // defineProperty replaces it with the parsed value
    Object.defineProperty(req, "query", {
      value: result.data,
      writable: true,
      configurable: true,
    });
    next();
  };