
@Injectable데코레이터와 함께 사용하는 클래스다.
NestInterceptor interface를 구현해야하는 것이다.
메서드 실행 전/후에 추가적인 로직 추가
function으로부터 반환된 결과를 변환하거나 발생된 예외를 변환한다.
function 기능 확장 및 function override
등을 할 수 있다
각 Interceptor는 intercept()메서드를 구현한다. 인자는 ExecutionContext와 Call Handler를 받는다. 각 인자에 대한 설명은 아래에 자세히 설명하겠습니다.
guards에서 나왔던 그 친구맞고, ArgumentHost를 확장함에 따라 헬퍼 메서드를 추가시켜준다. generic interceptor구축 시 도움을 준다.
Call Handler는 interceptor에서 특정 시점에 라우트 핸들러 메서드를 호출하는데 사용할 handle()메서드를 구현한다.
처음은 사용자 interaction 기록을 위해 사용하는 것이다.예를 들어 비동기 이벤트 dispatching, timestamp 등이 있다. 아래의 예제를 보면서 이해해보자.
// logging.interceptor.ts
import {
Injectable,
NestInterceptor,
ExecutionContext,
CallHandler,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler):
Observable<any> {
console.log('Before...');
const now = Date.now();
return next
.handle()
.pipe(tap(() => console.log(`After... ${Date.now() - now}ms`)));
}
}
인터셉터 설정을 위해선 @UserInterceptors()데코레이터를 사용한다.
안에 인자를 설정할 수 있는 데코레이터라는 것을 확인할 수 있었고
controller-scoped, method-scoped 나 global-scoped 등이 가능하다
컨트롤러에
@UseInterceptors(LoggingInterceptor)
export class CatsController {}
작성하면된다.