Search code examples
nestjsclass-transformer

NestJS Validate Headers using class-transform example


I am trying to validate that the headers of the request contain some specific data, and I am using NestJS. I found this information. While this is what I want to do, and it looks proper, the ClassType reference does not exist, and I am not sure what to use instead.

From the example, the decorator is referring to.

request-header.decorator.ts

import { createParamDecorator, ExecutionContext } from '@nestjs/commom'
import { plainToClass } from 'class-transformer';
// The import below fails
import { ClassType } from 'class-transformer/ClassTransformer';
import { validateOrReject } from 'class-validator';

export const RequestHeader = createParamDecorator(
  async (value:  ClassType<unknown>, ctx: ExecutionContext) => {

    // extract headers
    const headers = ctx.switchToHttp().getRequest().headers;

    // Convert headers to DTO object
    const dto = plainToClass(value, headers, { excludeExtraneousValues: true });
    
    // Validate 
    await validateOrReject(dto);

    // return header dto object 
    return dto;
  },
);

Solution

  • Rather than passing the type through a decorator like this, I'd suggest making a custom decorator and setting the validateCustomDecorators option for the ValidationPipe to true. The decorator would look something like

    const Header = createParamDecorator((data: unknown, context: ExecutionContext) => {
      const req = context.switchToHttp().getRequest();
      if (data) {
        return req.headers[data];
      }
      return req.headers;
    });
    

    And now instead of @Header() from @nestjs/common you can you @Header() from this file and get the ValidationPipe to run after applying the appropriate type metadata