
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const now = Date.now();
return next
.handle()
.pipe(tap(() => console.log(`완료에 걸린 시간: ${Date.now() - now}ms`)));
}
}
이 코드는 NestJS에서 사용되는 인터셉터의 예시입니다.
LoggingInterceptor 클래스는 NestInterceptor를 구현합
intercept 메서드는 HTTP 요청이 처리되는 동안 실행됨
ExecutionContext은 현재 실행 컨텍스트에 대한 정보를 제공하고, CallHandler는 요청을 처리하는 데 사용됨
intercept 메서드는 Observable을 반환합니다. 이 Observable은 HTTP 요청을 처리하고 응답을 생성하는 데 사용됨
next.handle()은 다음 핸들러(예: 미들웨어 또는 컨트롤러)를 호출하여 요청을 처리하고 결과 Observable을 반환한다.
tap 연산자는 Observable이 방출하는 각 항목에 대해 주어진 동작을 수행합니다. 여기서는 응답이 처리되고 로깅 문이 출력된다.
마지막으로, pipe 메서드를 사용하여 tap 연산자를 적용한 후 최종 Observable을 반환한다.
결과적으로 이 코드는 HTTP 요청이 처리되는 데 걸린 시간을 로깅하여 요청의 성능을 모니터링할 수 있게 한다!