인터셉터(Interceptor)

2025. 5. 9. 14:50·NestJS/NestJS 문서화

인터셉터의 역할

인터셉터는 라우팅 실행 전과 실행 후 모두에 작업을 추가할 수 있습니다.

인터셉터가 할 수 있는 일들

메서드 실행 전후에 작업을 추가할 수 있습니다.

함수에서 반환된 결과를 변환할 수 있습니다.

함수에서 발생한 예외를 변환할 수 있습니다.

조건에 따라 함수를 재정의 할 수 있습니다.

인터셉터 구현

인터셉터는 NestInterceptor 인터페이스를 구현해야 합니다.

NestInterceptor 구현 시 intercept(context: ExcutionCentext, next: CallHandler) 메서드를 구현해야 합니다.

매개변수 context는 요청 정보를 담고 있습니다.

매개변수 next는 라우터가 실행할 함수입니다.

import { CallHandler, ExecutionContext, NestInterceptor } from '@nestjs/common';
import { map, Observable } from 'rxjs';

export class SerializeInterceptor implements NestInterceptor {
  intercept(
    context: ExecutionContext,
    next: CallHandler<any>,
  ): Observable<any> | Promise<Observable<any>> {
  
    console.log('라우팅 핸들러 실행 전');

    return next.handle().pipe(
      map((data: any) => {
        console.log('라우팅 핸들러 실행 후');
      }),
    );
  }
}

인터셉터 적용

전역 적용

const app = await NestFactory.create(AppModule);
app.useGlobalInterceptors(new LoggingInterceptor());

컨트롤러 혹은 메서드 적용

@UseInterceptors(new LoggingInterceptor())
export class CatsController {}

데이터 직렬화

데이터 직렬화는 데이터를 통신에 사용하기 위한 형태로 변환하는 과정입니다.

데이터 직렬화 직전에 클라이언트에 반환할 데이터가 결정되기 때문에 응답 데이터의 일부를 제외 혹은 수정 하기에 적절한 시점입니다.

 

예를 들어, 비밀번호 같은 데이터는 응답에서 제외해야 합니다. 또는 Date() 객체를 사용자의 국적 또는 위치에 맞게 변환해야 합니다.

 

데이터 직렬화는 두 가지 방법이 있습니다.

  1. ORM의 Model 이용
  2. DTO 이용

NestJS 문서에는 모델을 이용을 권장합니다. 하지만 하나의 모델은 여러 라우팅에서 사용되고, 라우팅에 따라 직렬화 하는 것이 불가능하기 때문에 권장하지 않습니다.

모델을 이용한 데이터 직렬화

모델을 이용해 데이터 직렬화를 하려면 두 단계를 거쳐야 합니다.

  1. 모델 파일 수정
  2. 컨트롤러에 인터셉터 추가 

모델 파일 수정

import { Exclude, Expose, Transform } from 'class-transformer';

export class UserEntity {
  id: number;
  firstName: string;
  lastName: string;

  @Exclude() // 속성 제외
  password: string;
  
  @Expose() // 속성 추가
  get fullName(): string {
    return `${this.firstName} ${this.lastName}`;
  }
  
  // 데이터 변환
  @Transform(({ value }) => value.name)
  role: RoleEntity;
}

컨트롤러에 인터셉터 추가

@UseInterceptors(ClassSerializerInterceptor)
@Get()
findOne(id): UserEntity {
  return await this.userService.findOne(id);
}

DTO를 이용한 직렬화

DTO를 이용해 데이터 직렬화를 하려면 세 단계를 거쳐야 합니다.

  1. DTO 수정
  2. 사용자 정의 인터셉터 작성
  3. 컨트롤러에 인터셉터 추가

DTO 수정

import { Expose } from 'class-transformer';

export class UserDto {
  @Expose()
  id: number;

  @Expose()
  email: string;
}

사용자 정의 인터셉터 작성

import { CallHandler, ExecutionContext, NestInterceptor } from '@nestjs/common';
import { plainToClass } from 'class-transformer';
import { map, Observable } from 'rxjs';

export class SerializeInterceptor implements NestInterceptor {
  constructor(private dto: any) {}

  intercept(
    context: ExecutionContext,
    next: CallHandler<any>,
  ): Observable<any> | Promise<Observable<any>> {
    return next.handle().pipe(
      map((data: any) => {
        return plainToClass(this.dto, data, {
          excludeExtraneousValues: true,
        });
      }),
    );
  }
}

컨트롤러에 인터셉터 추가

@UseInterceptors(new SerializeInterceptor(UserEntity))
@Get()
findOne(id): UserEntity {
  return await this.userService.findOne(id);
}

데코레이터를 사용한 인터셉터 적용

인터셉터 적용 코드가 너무 길다면 데코레이터를 사용해 코드 작성을 줄일 수 있습니다.

 

아래 함수를 작성하면 @UseInterceptors() 데코레이터 대신 @Serialize() 데코레이터를 사용할 수 있습니다.

export function Serialize(dto: any) {
  return UseInterceptors(new SerializeInterceptor(dto));
}

 

저작자표시 (새창열림)

'NestJS > NestJS 문서화' 카테고리의 다른 글

사용자 정의 데코레이터(Custom Decorator)  (0) 2025.05.09
미들웨어(Middleware)  (0) 2025.05.09
가드(Guard)  (0) 2025.05.09
파이프(Pipe)  (0) 2025.05.02
모델과 DTO  (0) 2025.05.02
'NestJS/NestJS 문서화' 카테고리의 다른 글
  • 사용자 정의 데코레이터(Custom Decorator)
  • 미들웨어(Middleware)
  • 가드(Guard)
  • 파이프(Pipe)
남느
남느
  • 남느
    남느
    남느
  • 전체
    오늘
    어제
    • 분류 전체보기 (64)
      • 프로그래밍 (15)
      • 웹 기초 지식 (2)
      • Node.js 기초 (1)
      • 알고리즘(Node.js) (1)
      • NestJS (20)
        • NestJS 문서화 (14)
        • NestJS 레시피 (2)
        • NestJS 게시판 API 프로젝트 (4)
      • TypeORM (5)
      • 우분투 적응기 (8)
      • 리눅스 답은 하모니카다 (4)
      • 자바 (1)
      • 살다보니 드는 생각들 (2)
      • 도커 (1)
  • 블로그 메뉴

    • 홈
    • 태그
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    웹
    신입
    취업
    개발자
    프로그래머
    백엔드
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
남느
인터셉터(Interceptor)
상단으로

티스토리툴바