All files / src/decorators http-request-headers.decorator.ts

0% Statements 0/18
0% Branches 0/4
0% Functions 0/1
0% Lines 0/17

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                                                                 
import { BadRequestException, createParamDecorator, ExecutionContext } from '@nestjs/common';
import { plainToInstance } from 'class-transformer';
import { validateSync } from 'class-validator';
import { Request } from 'express';
import { traverseValidationError } from 'src/exception/exception.utils';
 
export const HttpRequestHeaders = createParamDecorator((_, ctx: ExecutionContext) => {
  const handler = ctx.getHandler();
  const target = ctx.getClass();
 
  const paramTypes = Reflect.getMetadata('design:paramtypes', target.prototype, handler.name);
  const dtoClass = paramTypes?.[0];
 
  /** Skip if it's a primitive or no class found */
  Iif (!dtoClass || [String, Number, Boolean, Object, Array].includes(dtoClass)) return {};
 
  /** extract headers */
  const headers = ctx.switchToHttp().getRequest<Request>().headers;
 
  /** Convert headers to DTO object */
  const dto: any = plainToInstance(dtoClass, headers, { excludeExtraneousValues: true });
 
  /** Validate */
  const errors = validateSync(dto);
  Iif (errors?.length) {
    const formattedErrors = traverseValidationError(errors);
    throw new BadRequestException(formattedErrors);
  }
 
  /** return header dto object */
  return dto;
});