英文:
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<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 object. 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 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论