Skip to content

拦截器

向军大叔每晚八点在 抖音bilibli 直播

拦截器是在请求前后对数据进行拦截处理。

定义拦截器

下面是使用拦截器对所有响应数据以data属性进行包裹。

import { CallHandler, ExecutionContext, Injectable, Logger, NestInterceptor } from '@nestjs/common'
import { Request } from 'express'
import { map } from 'rxjs/operators'

@Injectable()
export class TransformInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler) {
    console.log('拦截器前')
    const request = context.switchToHttp().getRequest() as Request
    const startTime = Date.now()
    return next.handle().pipe(
      map((data) => {
        const endTime = Date.now()
        new Logger().log(`TIME:${endTime - startTime}\tURL:${request.path}\tMETHOD:${request.method}`)
        return {
          data,
        }
      }),
    )
  }
}

注册拦截器

我们可以在控制器、模块、全局注册拦截器。

控制器中定义拦截器

@UseInterceptors(new TransformInterceptor())
export class CatsController {}

模块定义拦截器

@Module({
  providers: [
    {
      provide: APP_INTERCEPTOR,
      useClass: TransformInterceptor,
    },
  ],
})
export class AppModule {}

全局注册拦截器

const app = await NestFactory.create(ApplicationModule);
app.useGlobalInterceptors(new TransformInterceptor());