拦截器有一组有用的功能,这些功能是受面向方面编程(AOP)技术启发的。它们可以:
- 执行前/执行后附加逻辑方法
- 转换函数返回的结果
- 转换从函数引发的异常
- 扩展基本函数行为
- 根据特定条件完全重写函数(例如,出于缓存目的)
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from "@nestjs/common"
import { Observable } from "rxjs"
import { tap } from "rxjs/operators"
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
console.log("before")
const start = Date.now()
return next
.handle()
.pipe(
tap(() => console,log(`After...${Date.now() - now}ms`))
)
}
}
binding interceptors
@UseInterceptors(LoggingInterceptor) // 可以使用类或者实例
// @UseInterceptors(new LoggingInterceptor())
export class CatsController {}
全局使用拦截器
// app.useGlobalInterceptors(new LoggingInterceptor()); // 不能使用 上下文不一致
import { Module } from "@nestjs/common"
import { APP_INTERCEPTOR } from "@nest/core"
@Module({
providers: [
{
provide: APP_INTERCEPTOR,
useClass: LoggingInterceptor
}
]
})
export class AppModule {}