NodeJS

[Nestjs TIP] Request Header에 validate 처리

lahuman 2024. 6. 17. 17:16
728x90

Nestjs에서 Request Header validate 처리 방법

Validate Headers 를 참고해서 처리 했습니다.

validateCustomDecorators 옵션을 true롤 꼭 설정 해야 합니다.

// main.ts
async function bootstrap() {
  // ... 
  app.useGlobalPipes(
    new ValidationPipe({
      validateCustomDecorators: true // <-- Add this to allow the validation pipe to work with our custom decorator
    })
  );
  // ...
}
bootstrap();

// request-header.decorator.ts
export const RequestHeaders = createParamDecorator(
  async (property: string | number | symbol, ctx: ExecutionContext) => {
    const headers = ctx.switchToHttp().getRequest().headers;

    if (
      typeof property === 'string' ||
      typeof property === 'number' ||
      typeof property === 'symbol'
    ) {
      return headers[property];
    }

    return headers;
  },
);

// refresh-header.dto.ts
export class RefreshHeaderDTO {
  @IsString()
  @IsDefined()
  @Expose({ name: 'authorization' })
  authorization: string;
}


// app.controller.ts
@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  ApiOperation({ summary: '사용자 토큰 만료시 refresh 토큰으로 호출' })
  @Post('/refresh')
  refresh(@RequestHeaders() headers: RefreshHeaderDTO) {
    return this.userService.tokenRefresh(
      headers.authorization.split('Bearer ')[1],
    );
  }
}

사용한 전체 코드는 daily-quest에서 확인 가능합니다.

참고 자료

728x90