Middleware is a function which is called before the route handler. Middleware functions have access to the request and response objects, and the
next()
middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable namednext
.
NestJS에서 middleware는 라우트 핸들러 전에 호출되는 function 입니다. middlware function은 request와 response 객체에 접근할 수 있고 어플리케이션 request - response 주기에 있는 next() 함수에 접근할 수 있습니다.
middleware 함수는 아래의 작업 수행할수 있다고 합니다.
middleware는 2가지 방법으로 만들수 있는데 하나는 class형으로 만든 뒤 module에 DI를 할 수 있고 하나는 function으로 만든뒤 app.use()를 통해 선언할 수 있습니다.
$ nest g mi cats
import { Injectable, NestMiddleware } from '@nestjs/common';
@Injectable()
export class CatsMiddleware implements NestMiddleware {
use(req: any, res: any, next: () => void) {
next();
}
}
이렇게 쉽게 middleware를 만들 수 있습니다.