-
[Nestjs TIP] Request Header에 validate 처리NodeJS 2024. 6. 17. 17:16728x90
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'NodeJS' 카테고리의 다른 글
nestjs에서 guard에 Global service Inject 처리 (0) 2024.06.20 [Nestjs TIP] whitelist 사용시 주의점! (0) 2024.06.18 nestjs에서 registerAsync 사용시 isGlobal 설정 (0) 2024.06.12 nestjs에서 swagger사용시, generic 타입에 대한 response schema 처리 (0) 2023.06.05 정규식을 이용해서 package-lock.json의 주소를 변경 처리 (0) 2023.06.02