在Nest.js的Swagger规范中是否可以使用泛型类型?

huangapple go评论68阅读模式
英文:

Is it possible to have generic type in swagger spec in nest js?

问题

I'm implementing a POST endpoint which takes such a DTO as an input:

export class GenericEventDto<D, A> {
  @ApiProperty({ type: D }) // <- does not work
  @Expose()
  data: D

  @ApiProperty({ type: A })
  @Expose()
  attributes: A // <- same

  @ApiProperty()
  @Expose()
  messageId: string
}

In swagger docs data and attributes props appear to be empty objects. Controller code looks like this:

export class Controller {
  @ApiBody({ type: GenericEventDto<ConcreteData, ConcreteAttributes> })
  async handleIncomingMessage(
    @Body() event: GenericEventDto<ConcreteData, ConcreteAttributes>
  ): Promise<void> {
    // do smth
  }
}

Is it possible to have a generic type in the swagger spec? This GenericEventDto will be reused later for other endpoints, and I would like to avoid code duplication.

英文:

I'm implementing a POST endpoint which takes such a DTO as an input:

export class GenericEventDto&lt;D, A&gt; {
  @ApiProperty({ type: D }) // &lt;- does not work
  @Expose()
  data: D

  @ApiProperty({ type: A })
  @Expose()
  attributes: A // &lt;- same

  @ApiProperty()
  @Expose()
  messageId: string
}

In swagger docs data and attributes props appear to be empty object. Controller code looks like this:

export class Controller {
  @ApiBody({ type: GenericEventDto&lt;ConcreteData, ConcreteAttributes&gt; })
  async handleIncomingMessage(
    @Body() event: GenericEventDto&lt;ConcreteData, ConcreteAttributes&gt;
  ): Promise&lt;void&gt; {
    // do smth
  }
}

Is it possible to have generic type in swagger spec? This GenericEventDto will be reused later for other endpoints and I would like to avoid code duplication

答案1

得分: 0

文档明确提到了这一点

由于 TypeScript 不会存储关于泛型或接口的元数据,因此当您在DTO中使用它们时,SwaggerModule 可能无法在运行时正确生成模型定义

您需要创建一个混合而不是泛型类型。在这种情况下,混合是一个返回类定义的函数。

英文:

The docs specifically mention about this

> Since TypeScript does not store metadata about generics or interfaces, when you use them in your DTOs, SwaggerModule may not be able to properly generate model definitions at runtime

You'd need to make a mixin rather than a generic type. A mixin in this case is a function that returns a class definition

huangapple
  • 本文由 发表于 2023年6月15日 05:15:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76477586.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定