如何使用 DTO 将响应设置为 swagger 响应中的数组

har*_*bar 4 nestjs nestjs-swagger

some-dto.ts

    export class CreateCatDto {
      @ApiProperty()
      name: string;

      @ApiProperty()
      age: number;

      @ApiProperty()
      breed: string;
    }
Run Code Online (Sandbox Code Playgroud)

我不想要这样的回应:

  @ApiOkResponse(
      description: 'Cat object',
      type: CreateCatDto
    )
Run Code Online (Sandbox Code Playgroud)

但我的回应必须是像 dto 对象的数组。我想要 smth 像 soo

    ApiOkResponse(
          description: 'The record has been successfully removed.',
          schema: {
            type: 'array',
            properties: {
              obj: {
                type: CreateCatDto
              }
            }
          }
        )
Run Code Online (Sandbox Code Playgroud)

A. *_*tre 11

你有没有尝试过这样的事情:

@ApiOkResponse(
    description: 'Cat object',
    type: CreateCatDto,
    isArray: true // <= diff is here
)
Run Code Online (Sandbox Code Playgroud)

让我知道它是否有帮助


Rem*_*son 7

如果您需要处理多种类型:

@ApiOkResponse({
  description: 'More or less dangerous animals',
  schema: {
    type: 'array',
    items: {
      oneOf: [
        { $ref: getSchemaPath(CreateCatDto) },
        { $ref: getSchemaPath(CreateAlligatorDto) }
      ],
    },
  },
})
Run Code Online (Sandbox Code Playgroud)

此外,您可能需要事先将它们包含在控制器中:

@Controller("noahsark")
@ApiExtraModels(CreateCatDto, CreateAlligatorDto)
export class NoahsArkController {
...
}

Run Code Online (Sandbox Code Playgroud)


har*_*bar 5

我找到了另一个解决方案,我们可以像这样包装在数组中

@ApiOkResponse(
  description: 'Cat object',
  type: [CreateCatDto]
)
Run Code Online (Sandbox Code Playgroud)