Map strings to Array on Open API and NestJS

563 Views Asked by At

I aim to generate the swagger spec through a NestJS project, and It's all working until now. The problem arises when I want to specify that return data is a Dict that maps a key to an array of custom objects on runtime.

I read the documentation here https://swagger.io/docs/specification/data-models/dictionaries/ and some related content and got that I can create a map of strings to any object, but I couldn't relate to typed Arrays.

It's important to note that I don't know what the keys would be and how many objects would be contained in each Array, I just know that the value would be an Array of a specific type.

This is an example of my data:

{
  "1":[CustomObjectType, CustomObjectType, CustomObjectType],
  "5":[CustomObjectType, CustomObjectType]
}

So I think on Swagger it should be something like:

components:
  schemas:
    CustomMap:
      type: object
      additionalProperties:
        $ref: '#/components/schemas/CustomObjectType'
        isArray: true

    CustomObjectType:
      type: object
      ...

But I can't get it correctly. If I discover how I do it in Swagger, I can figure out how to pass it to NestJS.

I tried to use a class as type, but it doesn't map properties:

export class CustomObjectDTO {
  [x: string]: Array<CustomObjectType>;
}

My last attempt was by using @ApiResponse

@ApiResponse({
    status: 200,
    schema: {
      type: 'object',
      additionalProperties: {
        type: getSchemaPath(CustomObjectType),
      },
    },
  })

and it was almost what I need, but it misses that the value is actually and Array of CustomObjectType

1

There are 1 best solutions below

0
On

Solution moved from @lia's question post.

Found a solution by using value type as Array and defining the item's type as my CustomObjectType. Example:

components:
  schemas:
    CustomMap:
      type: object
      additionalProperties:
        type: array
        items:
          $ref: '#/components/schemas/CustomObjectType'      
    CustomObjectType:
      type: object