【问题标题】:@nestjs/swagger: How to add schema without @ApiOkResponse decorator?@nestjs/swagger:如何在没有 @ApiOkResponse 装饰器的情况下添加架构?
【发布时间】:2021-10-30 20:17:06
【问题描述】:

我有两个 DTO。用户 DTO 和用户 DTO。 UsersDTO 大摇大摆地显示,因为我有一个端点来获取用户列表,对于那个端点我有

  @ApiOkResponse({
    status: HttpStatus.OK,
    type: UsersDTO,
  })

在 UsersDTO 中,我使用 $ref 来使用 UserDTO。 UsersDTO 看起来像

export class UsersDTO {
  @ApiProperty({
    type: 'array',
    items: { $ref: getSchemaPath(UserDTO) },
  })
  @IsArray()
  readonly items: UserDTO[];

  @ApiProperty({
    type: 'object',
    properties: {
      totalItems: {
        type: 'number',
        example: 100,
      },
      itemCount: {
        type: 'number',
        example: 10,
      },
      itemsPerPage: {
        type: 'number',
        example: 10,
      },
      totalPages: {
        type: 'number',
        example: 10,
      },
      currentPage: {
        type: 'number',
        example: 2,
      },
    },
  })
  @IsObject()
  readonly meta: IMeta;
}

但它不招摇。 Swagger 将 [string] 显示为 items 的值。

有没有办法让它工作?

【问题讨论】:

    标签: javascript node.js swagger nestjs nestjs-swagger


    【解决方案1】:

    看起来您没有另一个端点在 @ApiOkResponse 中使用 UserDTO,例如

    @ApiOkResponse({
        status: HttpStatus.OK,
        type: UserDTO,
      })
    

    这意味着 Swagger 不能在 Schemas 之间进行引用。

    如果您添加另一个端点,例如获取单个用户,并使用提供的@ApiOkResponse,它将起作用。

    但是,如果您不需要该端点,您也可以通过以下方式在设置阶段向 Swagger 提供 DTO 架构

        const document = SwaggerModule.createDocument(
          app,
          new DocumentBuilder()
            .setTitle('API')
            .setDescription('API')
            .setVersion('1.0')
            .addBearerAuth()
            .build(),
          { extraModels: [UserDTO] },
        );
    
        SwaggerModule.setup(swaggerPath, app, document);
    
    

    您可以使用它直接使用@ApiOkResponse 装饰器添加端点中未使用的模式。 extraModels 是一个带有所需架构的数组

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-24
      • 2015-05-20
      • 1970-01-01
      • 2018-12-17
      • 2017-05-29
      • 2015-11-17
      • 2022-12-28
      • 2014-04-21
      相关资源
      最近更新 更多