NestJS中单个HTTP方法能否配置多个Interceptor?
NestJS中为单个HTTP方法配置多个Interceptor的方案
完全可以在NestJS的单个HTTP方法上配置多个Interceptor,包括内置的FileInterceptor和自定义的统一响应Interceptor,NestJS原生支持这种场景。
实现方式
有两种常见的绑定方式,效果一致,可根据习惯选择:
1. 叠加多个@UseInterceptors()装饰器
直接在路由方法上方依次添加多个@UseInterceptors(),每个装饰器传入一个Interceptor:
import { Controller, Post, UseInterceptors, UploadedFile } from '@nestjs/common'; import { FileInterceptor } from '@nestjs/platform-express'; import { UnifyResponseInterceptor } from './unify-response.interceptor'; @Controller('upload') export class UploadController { @Post() // 先绑定文件上传的FileInterceptor @UseInterceptors(FileInterceptor('file')) // 再绑定统一响应结构的自定义Interceptor @UseInterceptors(UnifyResponseInterceptor) uploadFile(@UploadedFile() file: Express.Multer.File) { return { filename: file.filename, size: file.size, }; } }
2. 在单个@UseInterceptors()中传入多个Interceptor
将多个Interceptor作为参数传入同一个@UseInterceptors(),参数顺序即为请求阶段的执行顺序:
@Post() @UseInterceptors(FileInterceptor('file'), UnifyResponseInterceptor) uploadFile(@UploadedFile() file: Express.Multer.File) { return { filename: file.filename, size: file.size, }; }
执行顺序说明
NestJS的Interceptor遵循洋葱模型:
- 请求阶段:按装饰器的从上到下顺序(或数组参数的从左到右顺序)依次进入各个Interceptor
- 响应阶段:按相反顺序退出各个Interceptor
以上面的代码为例,请求时会先经过FileInterceptor处理文件上传逻辑,再进入UnifyResponseInterceptor;响应时则先由UnifyResponseInterceptor统一包装响应结构,再经过FileInterceptor的后续处理。
自定义统一响应Interceptor示例
这里提供一个简单的统一响应结构Interceptor实现,供参考:
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; @Injectable() export class UnifyResponseInterceptor implements NestInterceptor { intercept(context: ExecutionContext, next: CallHandler): Observable<any> { return next.handle().pipe( map(data => ({ code: 200, msg: '操作成功', data, })), ); } }
内容的提问来源于stack exchange,提问作者Roop kumar.R
相关产品推荐
相关产品推荐

