NestJS API Pipes,interceptors

Gyus·2022년 5월 18일
0
post-thumbnail

Pipes

파이프는 @Injectable decorator와 함께 어노테이트 된 클래스이다. 파이프는 PipeTransform 인터페이스를 인용 해야한다.

파이프는 클라이언트 요청에서 들어오는 데이터를 유효성 검사 및 변환을 수행하여 서버가 원하는 데이터를 얻을 수 있도록 도와주는 클래스

main.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';
import { HttpExceptionFilter } from './common/http-exception.filter';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe());
  app.useGlobalFilters(new HttpExceptionFilter());
  await app.listen(3000);
}
bootstrap();

app.useGlobalPipes(new ValidationPipe()); 를 추가해준다.

Interceptor

인터셉터는 AOP(관점 지향 프로그래밍)에 영향을 많이 받았습니다. 인터셉터를 이용하면 다음과 같은 기능을 수행할 수 있습니다.

  • 메서드 실행 전/후 추가 로직 바인딩
  • 함수에서 반환된 결과를 변환
  • 함수에서 던져진 예외를 변환
  • 기본 기능의 동작을 확장
  • 특정 조건에 따라 기능을 완전히 재정의(예: 캐싱)

interceptors

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

@Injectable()
export class SuccessInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      map((data) => ({
        success: true,
        data,
      })),
    );
  }
}

모든 API에 성공했을시 response형식을 만들어서 출력시켜준다.

유저 조회 API를 실행시켰을 경우이다.

해당 controller에 interceptor를 적용시켜줘야 가능하다.

@Controller('users')
@UseInterceptors(SuccessInterceptor)
export class UsersController {
  constructor(
    private readonly userService: UsersService,
    private readonly authService: AuthService,
  ) {}

AOP란?(**Aspect Oriented Programming)

관점지향 프로그래밍.

핵심기능과 부가기능을 나누어서 관심사를 분리시켜주는 개발방식

핵심기능은 각 모듈을 의미한다(Board, User)

부가기능은 logging, transaction등을 의미한다.

이로인해 얻을수 있는 장점은

  1. 중복되는 코드를 제거
  2. Unit Testing의 편의성 증가
  3. 유지보수성 향상이 있다.
profile
푸로구래머

0개의 댓글