차봇 Driver라는 프로젝트를 시작하며 ApolloServer
+ Prisma1
을 사용했을때 여러 문제점을 겪고 새로운 시니어 팀장님(3달만에 나가셨지만... 또륵...)이 합류하며 RestAPI로 스펙을 정하여 TS + Express 와 TS + NestJS 사이에서 고민하였습니다. Apollo Server Express를 사용하며 높은 자유도에 코드관리가 너무 어려웠던 터라 NestJS를 선택 하게 되었고 스터디를 할 시간적 여유도 없이 프로젝트를 시작하여 Middleware나 Guard등을 쓰면서도 어떤 순서대로 동작하는지 제대로 알지 못하고 썼다가 제대로 리팩토링을 하기 위해 NestJS
를 공부하려 합니다.
Request LifeCycle을 공부하기 전에
Middleware
Guard
Interceptor
Pipe
들에 대한 지식이 선행 되어 있으면 좋습니다.
각각의 설명은 NestJS 공식 Doc에 잘 정리 되어있습니다.
Nest applications handle requests and produce responses in a sequence we refer to as the request lifecycle. With the use of middleware, pipes, guards, and interceptors, it can be challenging to track down where a particular piece of code executes during the request lifecycle, especially as global, controller level, and route level components come into play. In general, a request flows through middleware to guards, then to interceptors, then to pipes and finally back to interceptors on the return path (as the response is generated).
NestJS Doc에 따르면 Request Lifecycle은 아래와 같습니다.
Middleware
→ Guard
→ Interceptor
→ Pipe
→ Application Logic
→ Interceptor
여기서 Middleware를 제외한 나머지에서 Exception이 발생 하면 ExceptionFilter가 실행 됩니다. 그림으로 도식화를 해 보면 아래와 같습니다.