【问题标题】:Use Interceptor inside another Interceptor In nestjs在nestjs中的另一个拦截器中使用拦截器
【发布时间】:2021-01-30 00:52:23
【问题描述】:

我正在创建一个拦截器,我想在里面使用 FileInterceptor,但在 FileInterceptor 之后出现错误声明

import { CallHandler, ExecutionContext, Injectable, NestInterceptor, UseInterceptors } from '@nestjs/common';
import { Observable } from 'rxjs';
import { FileInterceptor } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import { extname } from 'path';

@Injectable()
export class UploaderInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {

    @UseInterceptors(FileInterceptor('file', {
      storage: diskStorage({
          destination: './uploads'
          , filename: (req, file, cb) => {
              // Generating a 32 random chars long string
              const randomName = Array(32).fill(null).map(() => (Math.round(Math.random() * 16)).toString(16)).join('')
              //Calling the callback passing the random name generated with the original extension name
              cb(null, `${randomName}${extname(file.originalname)}`)
          }
      })
  }));


    return next.handle();
  }
}

【问题讨论】:

  • 为什么要在拦截器中使用拦截器?您只需要扩展功能吗?目前,该拦截器不适用,在 NestJS 中,UseInterceptors() 装饰器仅在您将其绑定到控制器或路由处理程序时适用。
  • @JayMcDoniel 是的,我想扩展功能。基本上我想要什么而不是调用 FileInterceptor 并提供所有参数我只会调用 UploaderInterceptor 而这个拦截器会做剩下的事情
  • 我发现在这里使用别名效率更高。像 export const UploadInterceptor = FileInterceptor(config) 这样的东西,然后使用 @UseInterceptors(UploadInterceptor) 而不是使用这样的 TS 类的东西。
  • @JayMcDoniel 但如果不使用 UseInterceptors,FileInterceptor 将无法工作。你能把你想说的话写成代码吗
  • @JayMcDoniel 但不使用 UseInterceptors FileInterceptor 将如何工作

标签: node.js nestjs nestjs-gateways


【解决方案1】:

FileInterceptor 是一个mixin 意味着它是一个返回类的函数。此函数接受拦截器实际使用的配置。您可以做的不是尝试创建一个在后台使用拦截器或扩展它的类,而是为配置创建一个别名,如下所示:

export const UploadInterceptor = FileInterceptor('file', {
  storage: diskStorage({
      destination: './uploads',
      filename: (req, file, cb) => {
        // Generating a 32 random characters long string
        const randomName = Array(32).fill(null).map(() => (Math.round(Math.random() * 16)).toString(16)).join('')
        //Calling the callback passing the random name generated with the original extension name
        cb(null, `${randomName}${extname(file.originalname)}`)
      }
  })
})

现在有了这个导出的常量(实际上是一个类),你就可以像这样使用拦截器了:

@Controller('upload')
export class UploadController {

  @UseInterceptors(UploadInterceptor)
  @Post()
  uploadFile() {
  // do logic;
  }
}

一切都应该适合你。

【讨论】:

  • 但不使用 UseInterceptors FileInterceptor 将如何工作。
  • @AkhileshJha 就像我一开始说的,FileInterceptor 只不过是一个返回类的函数。综上所述,UploadInterceptor 本质上是FileInterceptor(config) 的别名。在制作这个别名时没有理由使用@UseInterceptor(),只有在将拦截器绑定到控制器或路由时才有必要。您也可以在我的回答中看到,这正是发生的情况。
猜你喜欢
  • 2020-12-16
  • 1970-01-01
  • 2015-11-22
  • 2014-03-10
  • 2021-08-08
  • 2022-06-14
  • 2020-01-03
  • 2020-12-12
  • 2013-06-25
相关资源
最近更新 更多