https://docs.nestjs.com/middleware
Middleware
- Middleware 란 route handler 이전에 호출되는 함수이다.
- 미들웨어 함수는 어플리케이션의 요청-응답 사이클에서
request
와 response
오브젝트와 next()
(미들웨어 함수) 에 접근한다.
next()
미들웨어 함수는 일반적으로 next
라는 이름을 가진 변수로 denoted(표시) 된다.
- 네스트 미들웨어는 기본적으로, express 의 미들웨어와 동일합니다.
- The following description from the official express documentation describes the capabilities of middleware :
Middleware functions can perform the following tasks:
- execute any code.
- make changes to the request and the response objects. (요청과 응답 오브젝트를 변경 할수 있다.)
- end the request-response cycle. (요청과 응답 사이클을 종료할 수 있다)
- 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() 함수를 호출하여, 다음 미들웨어 함수에 컨트롤을 넘겨야 한다. 그렇지 않으면 요청은 hanging 으로 남는다.
- 당신은 함수로나,
@Injectable()
데코레이션이 있는 class 로 커스텀 네스트 미들웨어를 만들 수 있습니다.
- 함수는 어떤 특별한 요구사항이 있지 않지만, class 는 반드시
NestMiddleware
interface 를 implement 해야 합니다.
- class method 를 이용하여 간단한 미들웨어 기능을 구현해봅시다.
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();
}
}
Dependency Injection
- 네스트 미들웨어는 의존성주입을 완벽하게 지원합니다.