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        39x 739x   2043x 2043x 24x         24x 24x   2019x 2019x     39x 73x   50x 50x 2x         2x 2x       48x         48x    
import { Request, Response, NextFunction } 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: ${JSON.stringify(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: ${JSON.stringify(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();
  };