【问题标题】:NestJs Swagger: How to define Api Property for dynamic classesNestJs Swagger:如何为动态类定义 Api 属性
【发布时间】:2021-11-14 16:59:21
【问题描述】:

我有以下课程

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

我应该如何定义 ApiProperty 类型?

【问题讨论】:

    标签: swagger nestjs nest openapi nestjs-swagger


    【解决方案1】:

    你可以用函数包装它

    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'){}
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 能否请您在这里添加一个关于手动更改的小示例,它应该是什么样子
      【解决方案3】:

      看看这个

      https://docs.nestjs.com/custom-decorators#decorator-composition

      您可以实现另一个装饰器来扩展 ApiProperty

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

      【讨论】:

        猜你喜欢
        • 2020-05-04
        • 2016-09-17
        • 2021-09-19
        • 2020-08-04
        • 2021-04-18
        • 2019-05-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多