【发布时间】: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