커스텀 데코레이터 & 인터셉터

커스텀 데코레이터

// decorators/current-user.decorator.ts

import {
  createParamDecorator,
  ExecutionContext
} from '@nestjs/common'

export const CurrentUser = createParamDecorator(
  (data : any, context : ExecutionContext) => {
    return 'hi there!'
  }
)
//users.controller.ts
  import { CurrentUser } from './decorators/current-user.decorator'

  @Get('/whoami')
  whoAmI(@CurrentUser() user : string) {
    return user;
  }

함수를 만들듯이 createParamDecorator를 데코레이터를 만들어 처리하는 데코레이터를 만든다.

인터셉터

데코레이터를 사용함으로서, 가독성이 좋아질 수 있다.

인터셉터를 의존성 주입과 연결하기

아래 소스는 컨트롤러에만 Interceptor를 설정

작성한 CurrentUserInterceptor를 provider에 넣어준다.

전역 인터셉터

Last updated