All files / redis-smq-api/src/middlewares request-validator.ts

100% Statements 16/16
85.71% Branches 6/7
100% Functions 4/4
100% Lines 15/15

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  57x 57x     57x       990x 57x 57x 88x 44x       44x 41x       3x   3x 3x           57x 56x      
import { ClassConstructor } from 'class-transformer';
import { validateDTO } from '../utils/validate-dto';
import { ERouteControllerActionPayload } from '../lib/routing';
import { TMiddleware } from '../types/common';
 
export function RequestValidator(
  dto: ClassConstructor<any>,
  payload: ERouteControllerActionPayload[],
): TMiddleware {
  return async (ctx, next) => {
    let plain: Record<string, any> = {};
    payload.forEach((i) => {
      if (i === ERouteControllerActionPayload.PATH) {
        plain = {
          ...plain,
          ...ctx.params,
        };
      } else if (i === ERouteControllerActionPayload.QUERY) {
        plain = {
          ...plain,
          ...ctx.query,
        };
      } else if (i === ERouteControllerActionPayload.BODY) {
        const body: Record<string | number, any> =
          typeof ctx.request['body'] === 'object' ? ctx.request['body'] : {};
        plain = {
          ...plain,
          ...body,
        };
      }
    });
    ctx.state.dto = await validateDTO(dto, plain);
    await next();
  };
}