typescript nestjs中带swagger的泛型类型响应

qni6mghb  于 2023-02-20  发布在  TypeScript
关注(0)|答案(1)|浏览(312)
export class PaginatedResult<T> {

 @Expose()
 @ApiResponseProperty(type: T}) // Unfortunately, this is not working beacue its a type but used as a value
 @Transform(({ obj }) =>
  obj.data.map((data) => new obj.classConstructor(data)),
 )
 data: T[];
}

如您所见,数据类型为T,它有Item或Tag等选项,但swagger始终只在端点上显示Item,我将ResponseType定义为:{type: PaginatedResult<Tag>}
有什么办法吗?

sbtkgmzw

sbtkgmzw1#

我找到了一个解决方案,但在外部,而不是属性本身,可以创建一个自定义ApiResponseDecorator,它接受泛型类型并用它填充一个模式:
(It的雀巢)

export const ApiOkResponseCustom = <GenericType extends Type<unknown>>(data: GenericType ) =>
  applyDecorators(
    ApiExtraModels(ModelWithGeneric, data),
    ApiOkResponse({
      description: `The paginated result of ${data.name}`,
      schema: {
        allOf: [
          { $ref: getSchemaPath(ModelWithGeneric) },
          {
            properties: {
              genericFieldName: {
                type: 'array',
                items: { $ref: getSchemaPath(data) },
              },},},],},}))

像这样使用:

@Controller('')
export class SomeController {

  @Get('/')
  ApiOkResponseCustom(GenericType)
  async get(): Promise<ModelWithGeneric<GenericType>> {}
}

相关问题