扩展 NestJS 装饰器

Extend NestJS decorator

我偶然发现了 this question,但我不想使用别名

我想扩展 express anyFilesInterceptor 以便我可以使用自定义文件对象。我不确定如何在 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;
  },
);

现在我可以从其他讨论和函数命名中看出 AnyFilesInterceptor 是一个 mixin,其中 returns 是 class 而 TestDecoratorcreateParamDecorator 创建可能只适用于参数。

NestJS 有办法创建 class 装饰器吗?或者扩展现有的装饰器?

实际上 AnyFilesInterceptor 本身就是一个生成拦截器的函数(它是实现 NestInterceptor 的任何 class)。
你可以通过用法看到它:虽然 'other' 拦截器可以通过简单地将 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
}