$ nest g interceptor <INTERCEPTOR_NAME>
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { Observable } from 'rxjs';
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
//...此處添加想設計的邏輯
return next.handle();
}
}
ExecutionContext是繼承ArguementsHost的類別,再多了可以取得Controller相關資訊的功能:
與Exception filter差不多,根據需求分成兩種:
1.只針對單一Handler:添加的@UseInterceptors(<INTERCEPTOR_NAME>)擺放位置在該Handler上
import { Controller, Get, UseInterceptors } from '@nestjs/common';
import { AppService } from './app.service';
import { LoggingInterceptor } from './interceptors/logging/logging.interceptor';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
@UseInterceptors(LoggingInterceptor)
getHello(): string {
return this.appService.getHello();
}
}
2.針對Controller中的所有Handler:@UseInterceptors(<INTERCEPTOR_NAME>)擺放位置在Controller上
import { Controller, Get, UseInterceptors } from '@nestjs/common';
import { AppService } from './app.service';
import { LoggingInterceptor } from './interceptors/logging/logging.interceptor';
@Controller()
@UseInterceptors(LoggingInterceptor)
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
}