[NestJS] Lifecycle Events

Hocaron·2022년 1월 31일
5

NestJS

목록 보기
10/12

Lifecycle Events

왜 알아야 할까?

프로젝트에서 Bootstrap 될 때, 호출되어야 하는 서비스가 있다. 예를 들자면 웹훅같은?
이것을 어떻게 호출할 것인가?! lifeCycle을 공부해서 해결해보자.

application이 구동되기 전에 어떤 일이 일어나는지 알아보자

  • Module initialized
  • BootStrap
  • Mapped route

Lifecycle sequence

  • NestJS는 내가 lifeCyle을 커스텀하게 다룰 수 있도록 5개의 훅을 제공한다.
Lifecycle hook methodLifecycle event triggering the hook method call
OnModuleInit()호스트 모듈이 초기화되면 호출
OnApplicationBootstrap()응용 프로그램이 완전히 시작되고 부트 스트랩되면 호출
OnModuleDestroy()Nest가 호스트 모듈을 파괴하기 직전에 정리
beforeApplicationShutdown()onModuleDestroy() 핸들러가 완료된 후에 호출
OnApplicationShutdown()시스템 신호에 응답합니다

사용 예시

  • 원하는 상황: NestJS가 Bootstrap 후에, 다른 API 호출이 없어도 구글로부터 response를 받고 싶다.
import {Injectable, OnApplicationBootstrap} from '@nestjs/common';
import {SchedulerRegistry} from '@nestjs/schedule';
import {CronJob} from 'cron';
import * as admin from 'firebase-admin';
import {ConfigService} from '@nestjs/config';
import {PubSub} from '@google-cloud/pubsub';
import {InjectRepository} from '@nestjs/typeorm';
import {User} from 'src/user/entities/user.entity';
import {Repository} from 'typeorm';
import {gmail} from '@googleapis/gmail';

@Injectable()
export class PushNotificationService implements OnApplicationBootstrap {
  constructor(
    private readonly schedulerRegistry: SchedulerRegistry,
    private readonly configService: ConfigService,
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
  ) {}

  onApplicationBootstrap() {
    // 메일 삭제 푸시 알림 작동
    this.sendDeleteMailPushNotification();

    // 환경 보호 정보 알릶 작동
    this.snedInformationPushNotification();
  }

  async sendDeleteMailPushNotification() {
    const auth = this.configService.get('googleAuth');
    const oAuth2Client = this.configService.get('googleOAuth2Client');

    const pubSubClient = new PubSub({auth});
    const subscription = pubSubClient.subscription(
      this.configService.get('googlePubSub').subscriptionName,
    );
 ...
  • npm run start로 시작하면, 다른 호출이 없어도 구글로부터 response가 온다!

Request lifecycle

왜 알아야 할까?

  • Request에 사용자 정보가 있어서 컨트롤러 전에서 검증(jwt)
  • Request 자체 데이터 타입을 검증(pipe)
  • response를 줄 때, 내가 원하는 response로 변경하여 반환
  • 에러 핸들링(Exception filter)

요청 생명주기

  1. Incoming request
  2. Globally bound middleware
  3. Module bound middleware
  4. Global guards
  5. Controller guards
  6. Route guards
  7. Global interceptors (pre-controller)
  8. Controller interceptors (pre-controller)
  9. Route interceptors (pre-controller)
  10. Global pipes
  11. Controller pipes
  12. Route pipes
  13. Route parameter pipes
  14. Controller (method handler)
  15. Service (if exists)
  16. Route interceptor (post-request)
  17. Controller interceptor (post-request)
  18. Global interceptor (post-request)
  19. Exception filters (route, then controller, then global)
  20. Server response

역시 글보다는 그림이지.

profile
기록을 통한 성장을

2개의 댓글

comment-user-thumbnail
2022년 4월 23일

안녕하세요 좋은글 감사합니다. 질문이 하나 있어요 Middleware가 ExceptionFilter에 밖에 그려져 있는데 왜 밖으로 그려져 있는지 알 수 있을까요?? Middleware에서 exception 발생 시 GlobalFilter가 작동을 하던데 그림이 저렇게 되는 이유를 알고싶네요..

1개의 답글