Http 통신이 이루어질 때 Host, URL, Method를 console 출력하는 간단한 Logger Middleware 작성
import { Injectable, NestMiddleware } from '@nestjs/common';
import { NextFunction, Request, Response } from 'express';
@Injectable()
export class LoggerMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction) {
console.log(
`HttpRequest... host: ${req.headers.host}, url: ${req.originalUrl}, method: ${req.method}`,
);
next();
}
}
nest g mi
를 통해 middlware 파일 생성
기본적으로 NestMiddleware를 implements
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Product } from './products/entities/products.entity';
import { ProductsModule } from './products/products.module';
import { CommonModule } from './common/common.module';
import { LoggerMiddleware } from './middleware/logger.middleware';
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'postgres',
host: 'localhost',
port: 5432,
username: 'postgres',
password: 'postgres',
database: 'nestjs',
entities: [Product],
synchronize: true,
logging: true,
}),
ProductsModule,
CommonModule,
],
controllers: [],
providers: [],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
// ProductsController 내에서 정의해둔 /product 경로에 대한 설정
consumer.apply(LoggerMiddleware).forRoutes('product');
}
}
.forRoutes({ path:'product', method: RequestMethod.GET });
특정 요청 method 유형을 제한
.forRoutes(ProductsController);
Controller class 사용 가능
HttpRequest... host: localhost:3000, url: /product, method: GET