본문 바로가기
NestJS

[NestJS] Middleware

by NJ94 2023. 9. 5.

😶 Middleware

라우터 핸들러 이전에 호출되는 함수.

 

미들웨어 기능은 요청/응답 개체에 엑세스할 수 있으며

next() 애플리케이션의 요청/응답 주기에 있는 미들웨어 기능도 있음

 

미들웨어 기능은 nest 로 표기됨

 

[Client Side] --- Http Request ---> [Middleware] ------> [Route Handler] @RequestMapping

 


  
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();
}
}

 

😶 의존성 주입

Nest 미들웨어는 종속성 주입을 완벽하게 지원한다.

 

Provider, Controller 와 마찬가지로 동일한 모듈내에서

사용 가능한 종속성을 주입 할 수 있다

-> constructor

 

 

😶 다중 미들웨어

메서드 내부에 쉼표로 구분된 목록을 제공하면 여러 미들웨어를 바인딩 가능함


  
consumer.apply(cors(), helmet(), logger).forRoutes(CatsController);

 

 

😶 Middleware Sample Code


  
import { Module, Global, NestModule, MiddlewareConsumer, RequestMethod } from '@nestjs/common';
import { LoggerMiddleware } from './common/middleware/logger.middleware';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { CatsModule } from './cats/cats.module';
import { CatsController } from './cats/cats.controller';
// @Global() : 모듈을 전역 범위로 만듬.
// . 전역 모듈은 일반적으로 루트 또는 코어 모듈에 의해 한 번만 등록되어야 함
@Module({
imports: [CatsModule],
controllers: [AppController],
providers: [AppService],
exports: [CatsModule] //export 사용 시, app.module.ts 모듈을 가져올 경우, CatsModule을 사용 가능.
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(LoggerMiddleware)
//ex)
.forRoutes(CatsController)
//ex1)
// .forRoutes('/cats')
//ex2)
// .forRoutes(
// {path: '/cats', method: RequestMethod.GET},
// {path: '/cats', method: RequestMethod.POST}
// )
//ex3. 특정 경로 제외
// .exclude(
// {path: '/cats', method: RequestMethod.GET},
// {path: '/cats', method: RequestMethod.POST},
// 'cats/(.*)'
// )
// .forRoutes(CatsController)
}
}
// 메서드 configure()는 다음을 사용하여 비동기식으로 만들 수 있습니다
// async/await(예: 메서드 본문 await내에서 비동기 작업을 완료 할 수 있음 configure()).

 

https://docs.nestjs.com/middleware

 

Documentation | NestJS - A progressive Node.js framework

Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Rea

docs.nestjs.com

'NestJS' 카테고리의 다른 글

[NestJS] Pipes  (0) 2023.09.06
[NestJS] exception-filters  (0) 2023.09.05
[NestJS] Modules  (0) 2023.09.05
[NestJS] Provider, IOC, DI  (0) 2023.09.05
[NestJS] SOLID  (0) 2023.09.04