Skip to content

拦截器是一个用 @Injectable() 装饰器注释的类,并实现 NestInterceptor 接口。

Interceptors 拦截器具有一系列实用功能,这些功能受到面向方面编程 (AOP) 技术的启发。它们可以实现以下功能:

  1. 在方法执行之前/之后绑定额外的逻辑
  2. 转换函数返回的结果
  3. 转换函数抛出的异常
  4. 扩展基本功能行为
  5. 根据特定条件完全覆盖函数(例如,出于缓存目的)

1.Usage

一个日志拦截器的基础使用形式如下:

ts
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 now = Date.now();
    return next
      .handle()
      .pipe(
        tap(() => console.log(`After... ${Date.now() - now}ms`)),
      );
  }
}

Nest 提供了 NestInterceptor 接口,该接口定义了一个 intercept() 方法,该方法接收两个参数:

  • context: ExecutionContext 对象,该对象包含当前正在处理的请求的详细信息。
  • next: CallHandler 对象,该对象包含 handle() 方法,该方法返回一个 Observable 对象。

2.Rxjs

TODO: