ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • NestJS Interceptor
    TIL. 2024. 7. 5. 03:47

    오늘은 

    NestJs Interceptor에 대하여 공부했습니다. 


    Request LifeCycle
    1. Incoming request
    2. Globally bound middleware, Module bound middleware
    3. Global guards, Controller guards, Route guards
    4. Global interceptors (pre-controller), Controller interceptors (pre-controller), Route interceptors (pre-controller)
    5. Global pipes, Controller pipes, Route pipes, Route parameter pipes
    6. Controller (method handler)
    7. Service (if exists)
    8. Route interceptor (post-request), Controller interceptor (post-request), Global interceptor (post-request)
    9. Exception filters (route, then controller, then global)
    10. Server response

     

    Intercpetor란 ? 

    Interceptor는 요청과 응답을 가로채서 변경을 가할 수 있는 컴포넌트입니다. 

     

    기능

    1. 메서드 실행 전/후 추가 로직 바인딩 

    2. 데이터 변환 

    3. 함수에서 반환된 결과 변환 

    4. 함수에서 던져진 예외 변환 

    5. 캐싱

    6. 성능 측정 

     

    로깅 인터셉터 예시

    import {
      CallHandler,
      ExecutionContext,
      Injectable,
      NestInterceptor,
    } from '@nestjs/common';
    import { Observable, tap } from 'rxjs';
    
    @Injectable()
    export class LoggingInterceptor implements NestInterceptor {  // NestInterceptor 인터페이스 구현
      
      intercept(
        context: ExecutionContext,
        next: CallHandler<any>,
      ): Observable<any> | Promise<Observable<any>> {
        
        console.log('Before log...');
    
        const now = Date.now();
    
        return next
          .handle()
          .pipe(tap(() => console.log(`After log... ${Date.now() - now} ms`)));
      }
    }

     

    Interceptor 파라미터 

    ExecutionContext CallHandler를 받아 처리합니다. 

     

    ExecutionContext

    ExecutionContext는 ArgumentsHost를 확장하여 현재 실행 프로세스에 대한 추가 세부 정보를 제공합니다. 

    ArgumentsHost는 핸들러에게 전달되는 인수 정보를 검색하기 위한 메서드를 제공합니다. 

    클라이언트의 요청 정보 (요청 데이터, 헤더 정보, 라우팅 경로, HTTP 메서드 등)와 같은 정보를 검색하고 파악합니다. 

     

    CallHandler

    Observable 객체인 CallHandler는 클라이언트 요청 경로로 라우팅 하는 역할을 합니다. CallHandler는 Interceptors 

    다음 생명주기로 넘어갈 때 사용되며, Return 타입이 Observable<T> 타입이므로 rxjs에 대한 이해도가 필요합니다. 

     

    Intercpetor 선언 

    1. 프로젝트 전체에 적용

    2. 특정 컨트롤러에 적용

    3. 특정 컨트롤러 라우트에 적용 

     

    예시는 제 프로젝트에 직접 적용해본 뒤 추가 업로드하도록 하겠습니다.

     

Designed by Tistory.