簡體   English   中英

擴展 NestJS 裝飾器

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM