【问题标题】:Extend NestJS decorator扩展 NestJS 装饰器
【发布时间】:2022-02-04 02:07:08
【问题描述】:

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

我想扩展 express anyFilesInterceptor 以便我可以使用自定义文件对象。我不确定如何在 NestJS 中扩展装饰器。

因此,作为一种解决方法,我尝试了 another question 的装饰器组合。但是,我只是尝试创建一个非常基本的(文档中的示例)装饰器时遇到错误

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,而由 createParamDecorator 创建的 TestDecorator 可能只适用于参数。

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

【问题讨论】:

    标签: javascript typescript nestjs decorator extends


    【解决方案1】:

    实际上AnyFilesInterceptor 是一个函数本身,它产生一个拦截器(它是任何实现NestInterceptor 的类)。
    您可以通过用法看到它:虽然可以通过简单地将类赋予 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,你只需要定义一个你自己的类拦截器:

    export class MyAllFilesInterceptor extends AnyFilesInterceptor() {
      // YOU MUST OVERRIDE THE `intercept` METHOD!
      // also, give options to the `AnyFilesInterceptor` method if you wish
    }
    

    【讨论】:

      猜你喜欢
      • 2020-06-26
      • 1970-01-01
      • 1970-01-01
      • 2016-08-18
      • 2016-07-18
      • 2013-02-19
      • 2017-03-06
      • 2020-08-20
      • 2017-11-19
      相关资源
      最近更新 更多