미들웨어
라우트 핸들러 이전에 호출되는 함수이다.
요청과 응답 사이에서 실행되며, 요청을 처리해서 특정 액션을 실행시킨다.
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(LoggerMiddleware)
.forRoutes('cats');
}
}
필터
예외 처리를 담당한다. 전역 필터와 로컬 필터로 나뉜다.
예외 필터는 로깅을 추가하거나 동적 요인에 따라 커스텀하기 위해 사용된다.
export class ForbiddenException extends HttpException {
constructor() {
super('Forbidden', HttpStatus.FORBIDDEN);
}
}
파이프
컨트롤러에 전달되는 인수를 검사하고, 수정하는 목적으로 사용된다.
내장 파이프가 존재하지만, 따로 커스텀 파이프를 만드는 것도 가능하다.
파이프는 여러 개를 이어서 사용할 수 있다.
@Get(':id')
async findOne(@Param('id', ParseIntPipe) id: number) {
return this.catsService.findOne(id);
}
인터셉터
미들웨어와 비슷한 역할을 하지만, 좀 더 세분화된 작업을 수행할 수 있다.
(요청과 응답 사이에서, 요청을 가로채 액션을 실행시키는)
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
console.log('Before...');
const now = Date.now();
return next
.handle()
.pipe(
tap(() => console.log(`After... ${Date.now() - now}ms`)),
);
}
}
주기
요청 -> 미들웨어 -> 가드 -> 인터셉터 -> 파이프 -> 컨트롤러 -> 서비스