framwork/NestJs

[NestJS] LifeCycle (생명주기)

닉네임없음ㅎ 2024. 7. 2. 18:52

 

[NestJS] LifeCycle (생명주기)

 

 

NestJS에서의 요청-응답 라이프사이클은 애플리케이션의 요청 처리 흐름을 이해하는데 중요하다. 
이 라이프사이클은 여러 단계를 거치며, 각 단계에서는 다양한 기능을 수행함. 


단계의 순서는 

MiddleWare -> Guard -> pre-interCeptor -> Pipe -> Controller -> post-interceptor -> ExceptionFilter -> Response

각 미들웨어, 가드, 인터셉터, 파이프는 모두 global하게 또는 controller , Route 에 적용할 수 있다. 

 



1. MiddleWare

-> 전역으로 적용된 미들웨어가 가장 먼저 실행된다. 
(예를들어, 'main.ts'파일에 app.use()로 바인딩된 미들웨어가 해당됨)
-> 미들웨어는 요청을 처리하기 전, 후에 실행될 수 있고 주로 요청 로깅, 본문 파싱, CORS 설정 등을 담당함. 

import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    console.log(`Request...`);
    next();
  }
}



2. Guard 

-> 주로 인증 및 권한 부여를 처리함
-> 사용자의 권한을 체크하는 로직이 들어가며, 요청이 컨트롤러에 도달하기 전에 실행됨. 
-> 가드는 'CanActivate' 인터페이스를 구현하여 작성함.

import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';

@Injectable()
export class AuthGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    return validateRequest(request);
  }
}



3. InterCeptor

-> 인터셉터는 컨트롤러에 도달하기 전과 응답을 클라이언트에 보내기 전에 바인딩할 수 있음.
-> 주로 로깅, 캐싱, 응답 변환할 때 사용함
-> 'NestInterceptor' 인터페이스를 구현하여 작성함. 

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

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



4. Pipe

-> 요청이 들어오는 파라미터의 유효성 검사 및 형 변환을 담당함
-> 주로 데이터 검증(Validation)과 변환(transformation)을 담당.
-> 'PipeTransform' 인터페이스를 구현하여 작성함

import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common';

@Injectable()
export class ValidationPipe implements PipeTransform {
  transform(value: any, metadata: ArgumentMetadata) {
    if (!isValid(value)) {
      throw new BadRequestException('Validation failed');
    }
    return value;
  }
}




5. Exception Filter

-> 예외 처리를 담당한다. 
-> 예를들어, 에러 메세지를 원하는 형태로 가공하여 응답할 수 있고,
'HttpException'을 모두 캐치하여 일관된 형태의 응답 메세지를 보낼 수 있음. 
-> 'ExceptionFilter' 인터페이스를 구현하여 작성함. 

import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const status = exception.getStatus();

    response.status(status).json({
      statusCode: status,
      timestamp: new Date().toISOString(),
      path: ctx.getRequest().url,
    });
  }
}

 


참고자료 
https://docs.nestjs.com/fundamentals/lifecycle-events#lifecycle-events-1