NestJS - Validate Header DTO

오픈소스·2024년 1월 10일
0

https://github.com/nestjs/nest/issues/356

[Feature request] Support pipes for headers

kamilmysliwiec commented on Jan 15, 2018
Hi @ssbarbeee,
That's not possible, see here #279
BUT there's a workaround. You can create a custom decorator for your headers https://docs.nestjs.com/custom-decorators, pipes run for them as well. 🙂

https://github.com/nestjs/nest/issues/279

[SUGGESTION] Let Headers decorators accepts pipes

kamilmysliwiec commented on Dec 9, 2017
Hi @wangzishi,
Why not parse token inside middleware / interceptor / guard? If we would allow binding pipes to headers, the global pipes (for example ValidationPipe) would run for them as well. I think it's redundant.


https://github.com/nestjs/nest/issues/4798

request-header.decorator.ts

import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import { plainToInstance } from 'class-transformer';
import { validateOrReject } from 'class-validator';

export const RequestHeader = createParamDecorator(async (value: any, ctx: ExecutionContext) => {
    // extract headers
    const headers = ctx.switchToHttp().getRequest().headers;

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

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

header.dto.ts

import { IsDefined, IsString } from "class-validator";

export class HeaderDTO {
    @IsString()
    @IsDefined()
    @Expose({ name: 'myheader1' })        // required as headers are case insensitive
    myHeader1: string;

    @IsString()
    @IsDefined()
    @Expose({ name: 'myheader1' })
    myHeader2: string;
}

excludeExtraneousValues

https://velog.io/@pk3669/plainToInstance-사용-경험

{ excludeExtraneousValues: true }@Expose() 없이,
@RequestHeader() 로만 사용하면 됩니다.

@Get('/hello')
getHello(@RequestHeader() headers: HeaderDTO) {
        console.log(headers);
    }
}

0개의 댓글