[英]Extend NestJS decorator
我偶然发现了这个问题,但我不认为我想使用别名
我想扩展 express anyFilesInterceptor
,以便可以使用自定义文件 object。 我不确定如何在 NestJS 中扩展装饰器。
因此,作为一种解决方法,我尝试了另一个问题的装饰器组合。 但是,我只是尝试创建一个非常基本的(文档中的示例)装饰器时遇到错误
import { applyDecorators, createParamDecorator, ExecutionContext } from "@nestjs/common";
import { AnyFilesInterceptor } from "@nestjs/platform-express";
export function Test() {
return applyDecorators(
AnyFilesInterceptor,
TestDecorator
)
}
export const TestDecorator = createParamDecorator(
(data: string, ctx: ExecutionContext) => {
const request = ctx.switchToHttp().getRequest();
const user = request.user;
return data ? user?.[data] : user;
},
);
现在我可以从其他讨论和 function 命名中看到AnyFilesInterceptor
是一个返回 class 的混合,而由createParamDecorator
创建的TestDecorator
可能仅适用于参数。
NestJS 是否有办法创建 class 装饰器? 或者扩展现有的装饰器?
实际上AnyFilesInterceptor
是一个 function 本身,它产生一个拦截器(它是任何实现 NestInterceptor 的NestInterceptor
)。
您可以通过用法看到它:虽然可以通过简单地将 class 提供给UseInterceptor()
装饰器来使用“其他”拦截器,但该拦截器需要调用(没有 new 关键字)。
例子:
@UseInterceptor(RegularInterceptor)
//or
@UseInterceptor(new RegularInterceptor())
// AnyFilesInterceptor is a function returning a class
@UseInterceptor(AnyFilesInterceptor())
//or
@UseInterceptor(new (AnyFilesInterceptor())({/* some multer options here */))
所以基本上如果你想扩展AnyFilesInterceptor
你只需要定义一个你自己的 class 拦截器:
export class MyAllFilesInterceptor extends AnyFilesInterceptor() {
// YOU MUST OVERRIDE THE `intercept` METHOD!
// also, give options to the `AnyFilesInterceptor` method if you wish
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.