how to set the response to be an array in the swagger response using DTOs
Asked Answered
S

3

19

some-dto.ts

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

      @ApiProperty()
      age: number;

      @ApiProperty()
      breed: string;
    }

I don't want response something like this:

  @ApiOkResponse(
      description: 'Cat object',
      type: CreateCatDto
    )

but my response must be array of like dto objects. I want smth like soo

    ApiOkResponse(
          description: 'The record has been successfully removed.',
          schema: {
            type: 'array',
            properties: {
              obj: {
                type: CreateCatDto
              }
            }
          }
        )
Sisterhood answered 9/3, 2020 at 11:6 Comment(0)
F
31

have you tried something like this:

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

Let me know if it helps

Freethinker answered 9/3, 2020 at 12:25 Comment(2)
Do you have an idea if you want to respond with a list of lists? Like CreateCatDto[][]?Bygone
I personally haven't had to deal with such structure in past experiences. You would have to check on the web to see if this is supported and how to implement. If supported my guess is that you would need to tweak things in order to make it work 🤔 Let us know if you find a solution though !Freethinker
S
15

I found another solution we can wrap in array like this

@ApiOkResponse(
  description: 'Cat object',
  type: [CreateCatDto]
)
Sisterhood answered 9/3, 2020 at 12:37 Comment(1)
Nice to know array type can be inferred from using the DTO type within an array !Freethinker
B
8

And if you need to deal with multiple types :

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

Additionally, you might need to include them in the controller beforehand :

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

Bergerac answered 1/7, 2022 at 14:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.