클라이언트로부터 들어온 요청을 각 컨트롤러의 요청 핸들러가 처리하기 이전에 코드를 실행할 수 있는 기능
요청(request) 및 응답(response) 객체에 접근할 수
일반적으로 next()라는 미들웨어 함수
Nest 미들웨어는 기본적으로 Express의 미들웨어와 동일
- 하나의 함수를 통해 구현
- @Injectable() 데코레이터가 있는 클래스로 구현 (NestMiddleware 인터페이스 구현)
// logger.middleware.ts;
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 미들웨어는 의존성 주입(Dependency Injection)을 완벽하게 지원 (동일한 모듈 내에서 사용할 수 있는 의존성을 주입)
@Module() 데코레이터를 설정하는 속성에는
imports, exports, providers 등만 있지
미들웨어를 설정하기 위한 속성은 없습니다
대신 모듈 클래스의 configure() 메서드를 사용하여 설정할 수 있습니다.
미들웨어를 포함하는 모듈은 NestModule 인터페이스를 구현
이제 Logger 미들웨어를 AppModule 수준에서 설정
// app.module.ts
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { LoggerMiddleware } from './common/middleware/logger.middleware';
import { CatsModule } from './cats/cats.module';
@Module({
imports: [CatsModule],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(LoggerMiddleware).forRoutes('cats');
}
}
https://www.wisewiredbooks.com/nestjs/overview/06-middleware.html
미들웨어 - 쉽게 풀어 쓴 Nest.js
미들웨어는 클라이언트로부터 들어온 요청을 각 컨트롤러의 요청 핸들러가 처리하기 이전에 코드를 실행할 수 있는 기능입니다. 미들웨어 함수는 애플리케이션의 요청-응답 주기에서 요청(reque
www.wisewiredbooks.com
'Wecode -기업협업 인턴 (부트캠프) > 기업협업 독학, 공부' 카테고리의 다른 글
기업협업 2번째 프로젝트: '문법' 오답노트 (0) | 2023.11.13 |
---|---|
Entity와 DTO 언제, 왜 쓰는지 (nestJS, typeorm ...) (0) | 2023.11.08 |
쿼리 빌더 Query Builder 왜, 언제, 어떻게 쓰는가 (0) | 2023.11.08 |
postgre docker (0) | 2023.11.08 |
github에 개인 정보, 비밀번호가 올라갔을 경우 [reset --hard], local commit 내역으로 확인! (0) | 2023.11.08 |