30-middleware
1. Middleware 이론

RequestMiddleware- Global Middleware
- Module Middleware
Guard- Global Guards
- Controller Guards
- Route Guards
Interceptors- Global Interceptors
- Controller Interceptors
- Route Interceptors
Pipes- Global Pipes
- Controller Pipes
- Route Pipes
- Route Parameter Pipes
ControllerServiceInterceptor- Router Interceptor
- Controller Interceptor
- Global Interceptor
Exception Filters- Route
- Controller
- Global
Response
미들웨어는 가장 쉽고 가장 단순하고 가장 어떻게 보면 원초적인 기능이다.

- 공식문서 : https://docs.nestjs.com/middleware
- 위 그림을 보면, 클라이언트 사이드에서 요청을 넣고, 라우트 핸들러까지 가기 전에 미들웨어를 거친다.
- 전체 그림을 봤을 때도, 미들웨어가 가장 먼저 요청을 받는 역할을 한다.
Middleware는 라우트 핸들러가 실행되기 전에 실행된다. Request와 Response 객체에 접근 할 수 있다.
Middleware는 다음과 같은 작업을 할 수 있다.
- 자유롭게 코드 실행
- 요청과 응답 객체를 변경
- 요청 응답 사이클 중단
- 다음 미들웨어 실행하기
1.1 Middleware란?
Nest 미들웨어는 기본적으로 Express 미들웨어와 동일하다. 공식 문서의 다음 설명은 미들웨어의 기능을 설명한다.
미들웨어 함수는 다음 작업을 수행할 수 있습니다.
- execute any code (어떤 코드든 실행할 수 있다.)
- make changes to the request and the response objects.
- 요청 및 응답 객체의 변화를 만들어 줄 수 있다.
- 무언가를 추가하거나 삭제, 업데이트 할 수 있다는 의미
- end the request-response cycle.
- 요청이 끝나게 중간에 중지할 수 있다.
- 일종의 guard 역할도 할 수 있다는 의미
- call the next middleware function in the stack.
- 스택에서 다음 미들웨어 함수를 호출힌다.
- 여러 개의 미들웨어를 순서대로 적용할 수 있는데, 적용된 순서대로 실행된다.
- 즉, 미들웨어를 여러 개를 엮을 수 있다는 의미
- if the current middleware function does not end the request-response cycle,
- it must call
next()to pass control to the next middleware function.- Otherwise, the request will be left hanging.
- 현재 미들웨어 함수가 요청-응답 주기를 종료하지 않는 경우, (=> 에러를 던지지 않는다면,)
- 다음 미들웨어 함수에 제어를 전달하기 위해
next()호출해야 한다.- 그렇지 않으면 요청이 중단된 상태로 남게 됩니다.
2. Middleware 사용법
2.1 Middleware 선언법
typescript
1import { Injectable, NestMiddleware } from '@nestjs/common'2import { Request, Response, NextFunction } from 'express'34@Injectable()5export class LogMiddleware implements NestMiddleware {6use(req: Request, res: Response, next: NextFunction) {7console.log(`[REQ] ${req.method} ${req.url} ${new Date().toLocaleString('kr')}`)8next()9}10}
2.2 Middleware 적용법
적용법 1 : 모듈에 적용
typescript
1import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common'2import { LoggerMiddleware } from './common/middleware/logger.middleware'3import { CatsModule } from './cats/cats.module'45@Module({6imports: [CatsModule],7})8export class AppModule implements NestModule {9configure(consumer: MiddlewareConsumer) {10consumer.apply(LoggerMiddleware).forRoutes('cats')11}12}
typescript
1import { Module, NestModule, RequestMethod, MiddlewareConsumer } from '@nestjs/common'2import { LoggerMiddleware } from './common/middleware/logger.middleware'3import { CatsModule } from './cats/cats.module'45@Module({6imports: [CatsModule],7})8export class AppModule implements NestModule {9configure(consumer: MiddlewareConsumer) {10consumer.apply(LoggerMiddleware).forRoutes({ path: 'cats', method: RequestMethod.GET })11}12}
적용법 2 : 컨트롤러에 적용
typescript
1forRoutes({ path: 'cats', method: RequestMethod.ALL })
typescript
1consumer2.apply(LoggerMiddleware)3.exclude(4{ path: 'cats', method: RequestMethod.GET }, //5{ path: 'cats', method: RequestMethod.POST },6'cats/(.*)',7)8.forRoutes(CatsController)
typescript
1consumer.apply(cors(), helmet(), logger).forRoutes(CatsController)
적용법 3 : 글로벌 미들웨어에 적용
typescript
1const app = await NestFactory.create(AppModule)2app.use(logger)3await app.listen(3000)
3. Middleware 사용
common/middleware/log.middleware.ts 파일을 만든다.
common/middleware/log.middleware.ts
1import { Injectable, NestMiddleware } from '@nestjs/common'2import { NextFunction } from 'express'34@Injectable()5export class LogMiddleware implements NestMiddleware {6use(req: Request, res: Response, next: NextFunction) {7console.log(`[REQ] ${req.method} ${req.url} ${new Date().toLocaleString('kr')}`)8next()9}10}
정확한 로그를 확인하기 위해 posts 컨트롤러에 적용한 Interceptors와 Filter를 주석처리한다.
posts.controller.ts
1/*** 1) GET /posts2* 모든 post를 다 가져온다3*/4@Get()5// @UseInterceptors(LogInterceptor)6// @UseFilters(HttpExceptionFilter)7getPosts(@Query() query: PaginatePostDto) {8// throw new BadRequestException('에러 테스트')9return this.postsService.paginatePosts(query)10}
미들웨어는 모듈에다가 적용해야 한다. posts 모듈에 위에 작성한 미들웨어를 적용한다.
posts.module.ts
1// posts.module.ts 생략2export class PostsModule implements NestModule {3configure(consumer: MiddlewareConsumer) {4consumer.apply(LogMiddleware).forRoutes({5path: 'posts*', // posts 뒤에 어떤 글자이든 적용(와일드카드)6// method: RequestMethod.ALL, // 모든 요청에 적용7method: RequestMethod.GET, // GET 요청만 적용8})9}10}
그런데 이렇게 특정 모듈에만 아니라 모든 모듈에 적용할 수 있다.
- 위에서 작성한 코드를 다시 원래대로
export class PostsModule{}만 남긴다. - 이렇게 하면 앱 전체 모든 라우트에 미들웨어를 적용해, 요청에 로그를 찍을 수 있다.
- 대용량 트래픽이 들어오는 트래픽들을 모니터링 시스템을 미들웨어로 만들면 유용하다.
app.module.ts
1// app.module.ts 생략2export class AppModule implements NestModule {3configure(consumer: MiddlewareConsumer) {4consumer.apply(LogMiddleware).forRoutes({5path: '*', // 뒤에 어떤 글자이든 적용(와일드카드)6method: RequestMethod.ALL, // 모든 요청에 적용7})8}9}