NestJs/Swagger(OpenAPI) defining nested objects in query parameters
04:52 07 Feb 2022

I'm trying to correctly define OpenAPI spec for the purposes of generating api client from that spec. I've encoutered a problem where we have a complex query object with nested objects and arrays of objects for get a GET route.

Lets take these classes as an example.

class Person {
  @ApiProperty()
  name!: string
  @ApiProperty()
  location!: string
}

class CompanyDto {
  @ApiProperty()
  name!: string

  @ApiProperty({
    type: [Person],
  })
  employees!: Person[]
}

And a get request with @Query decorator.

  @Get('test')
  async testing(@Query() dto: CompanyDto): Promise {
    // ...
  }

What I'm getting is.

    {
      get: {
        operationId: 'testing',
        parameters: [
          {
            name: 'name',
            required: true,
            in: 'query',
            schema: {
              type: 'string',
            },
          },
          {
            name: 'name',
            in: 'query',
            required: true,
            schema: {
              type: 'string',
            },
          },
          {
            name: 'location',
            in: 'query',
            required: true,
            schema: {
              type: 'string',
            },
          },
        ],
        responses: {
          '200': {
            description: '',
          },
        },
        tags: ['booking'],
      },
    }

I've also tries to define Query params by adding @ApiQuery decorator and it almost works.

  @ApiQuery({
    style: 'deepObject',
    type: CompanyDto,
  })

--

{
  get: {
    operationId: 'testing',
    parameters: [
      {
        name: 'name',
        required: true,
        in: 'query',
        schema: {
          type: 'string',
        },
      },
      {
        name: 'name',
        in: 'query',
        required: true,
        schema: {
          type: 'string',
        },
      },
      {
        name: 'location',
        in: 'query',
        required: true,
        schema: {
          type: 'string',
        },
      },
      {
        name: 'name',
        in: 'query',
        required: true,
        schema: {
          type: 'string',
        },
      },
      {
        name: 'employees',
        in: 'query',
        required: true,
        schema: {
          type: 'array',
          items: {
            $ref: '#/components/schemas/Person',
          },
        },
      },
    ],
    responses: {
      '200': {
        description: '',
      },
    },
    tags: ['booking'],
  },
}

However now I'm getting duplicate query definitions mashed in to one. Is there a way to prevent or overwrite @Query definition? Or just a better way to define complex @Query in general?

swagger nestjs openapi