
미들웨어란 라우트 핸들러 이전에 호출되는 함수
미들웨어 기능은 요청과 응답 개체에 엑세스
nest의 미들웨어는 기본적으로 express의 미들웨어와 등일함
함수또는 클래스를 미들웨어로 만들어 줄 수 있음
미들웨로 함수을 사용하면 조건이 없지만클래스의 경우에는 @Injectable() 데코레이터가 있어야 하고 NestMiddleware 인터페이스를 구현
미들웨어도 의존성을 주입할 수 있기때문에 constructor을 사용해 의존성 주입가능
모듈 데코레이터에는 미들웨어를 위한 부분이 존재하지 않음
대신 @configure 메소드를 사용해 설정할 수 있음
적용하기위해 NestModule 인터페이스를 구현해야함
import { Injectable, NestMiddleware, Logger } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
@Injectable()
export class LoggerMiddleware implements NestMiddleware {
private logger = new Logger('HTTP');
use(req: Request, res: Response, next: NextFunction): void {
const { method, originalUrl } = req;
const start = Date.now();
res.on('finish', () => {
const { statusCode } = res;
const delay = Date.now() - start;
this.logger.log(`${method} ${originalUrl} ${statusCode} ${delay}ms`);
});
next();
}
}
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { LoggerMiddleware } from './logger.middleware';
@Module({
imports: [],
controllers: [AppController],
providers: [AppService],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(LoggerMiddleware)
.forRoutes('*'); // 모든 라우트에 대해 미들웨어 적용
}
}
forRoute에 라우트를 지정해 미들웨어를 적용할 라우트를 지정할 수 있다
특정 메서드로 접근하게 하고 싶다면 forRoute에 path로 경로 method에 RequestMethod.으로 지정
위처럼 와일드 카드도 사용할 수 있읔
특정 경로를 제외하고 싶을때는 .exclude메서드를 통해 라우터 제외가능