NestJs Swagger:如何为动态类定义API Property

hs1ihplo  于 2023-10-18  发布在  其他
关注(0)|答案(4)|浏览(184)

我有低于类

export class DocumentsSteps {
    @ApiProperty({type: ???})
    [type: string]: DocumentStep;
}

如何定义ApiProperty类型?

xoefb8l8

xoefb8l81#

截至目前(2021年9月21日),Nest的@nestjs/swagger库不可能做到这一点,因为没有字段可以反映元数据。open a pull request可能有机会允许在库中使用dictionaries,但现在你最好的选择是修改Nest生成的swagger文档,然后自己添加它

oxiaedzo

oxiaedzo2#

你可以用一个函数来 Package 它

export type Constructor<I> = new (...args: any[]) => I

function ErrorDto(statusCode: number, message: string): Constructor<Error>{
  class Error implements Error{
    @ApiProperty({ example: statusCode })
    readonly statusCode: number

    @ApiProperty({ example: message })
    readonly message: string

  }
  return Error
}
export class UnauthorizedErrorDto extends ErrorDto(401, 'Unauthorized'){}
export class BadRequestErrorDto extends ErrorDto(400, 'Bad Request'){}
7fhtutme

7fhtutme3#

我找到了一个解决方案,它看起来有点丑陋的 Swagger ,但它是最好的可能的方法。
使用additionalProperties,您可以通过提供对Dto的引用来添加具有类型化值的动态键。Dto不会是其他响应的一部分,并且可能在swagger中不可用,要公开它,我们需要使用@ApiExtaModels()

@ApiExtraModels(DocumentStep)
export class DocumentsSteps {
    @ApiProperty({
        additionalProperties: { oneOf: [{ $ref: getSchemaPath(DocumentStep) }] },
    })
    [type: string]: DocumentStep;
}

结果类似于

aiqt4smr

aiqt4smr4#

看看这个
https://docs.nestjs.com/custom-decorators#decorator-composition
您可以实现另一个装饰器来扩展ApiProperty

export function CustomApiProperty(type: string) {
  return applyDecorators(
    ApiProperty({type, ...}),
  );
}

相关问题