[TIL] NestJS 공부 16일차

정인교·2021년 6월 19일
0

TIL(Today I Learned)

목록 보기
27/67
post-thumbnail

파이프 작업

NestJS에서 built-in된 @Body처럼 custom param decorator를 다룬다.
그렇기에, pipes가 실행이된다.

@Get()
async findOne(
  @User(new ValidationPipe({ validateCustomDecorators: true }))
  user: UserEntity,
) {
  console.log(user);
}

데코레이터 구성

데코레이터 구성을 위해 핼퍼 매서드가 제공되는데, 인증 관련 데코레이터를 하나로 결합한다고 했을 때 이렇게 할 수 있다.

import { applyDecorators } from '@nestjs/common';

export function Auth(...roles: Role[]) {
  return applyDecorators(
    SetMetadata('roles', roles),
    UseGuards(AuthGuard, RolesGuard),
    ApiBearerAuth(),
    ApiUnauthorizedResponse({ description: 'Unauthorized' })
  );
}

그런 다음

@Get('users')
@Auth('admin')
findAllUsers() {}

@Auth를 통해 사용할 수 있다.

profile
백엔드 개발자 정인교입니다!

0개의 댓글