Nest创建一个简单的拦截器
实现一个 NestInterceptor 类
具体代码如下👇:
1 | |
1、实现 NestInterceptor 类中的方法 intercept
intercept 函数两个参数
context: ExecutionContext 执行上下文 可以获取 getClass getHandlerCallHandler: 只有一个handle方法,返回一个Observable 监听响应数据流1
2
3
4
5
6
7
8
9
10
11export interface NestInterceptor<T = any, R = any> {
/**
* Method to implement a custom interceptor.
*
* @param context an `ExecutionContext` object providing methods to access the 执行上下文
* route handler and class about to be invoked.
* @param next a reference to the `CallHandler`, which provides access to an 返回一个Observable
* `Observable` representing the response stream from the route handler.
*/
intercept(context: ExecutionContext, next: CallHandler<T>): Observable<R> | Promise<Observable<R>>;
}
2、使用 rxjs 中的Observable 进行响应式编程
了解rxjs
什么是响应式编程呢,可以看看这个: 响应式编程(Reactive Programming)介绍
大概就是一个异步的、流式的编程方式
3、添加全局拦截器
给拦截器类添加注解 @Injectable()
在服务入口文件中(main.ts)中,调用Nest服务实例方法useGlobalInterceptors添加全局拦截器
1 | |
额外知识点: 返回值利用了协变原理
1 | |
Nest创建一个简单的拦截器
https://avatar0813.github.io/2023/06/08/nest/Nest创建一个简单的拦截器/