Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NestJS Swagger: Describe Map inside ApiProperty Decorator

I have an NestJS API in front of an InfluxDB. In the API I want to add property description via the ApiProptery decorator from nestjs/swagger.
My Problem here is that I don't know how to create a proper description for a map.

Here is my model:

import { Precision } from '../shared/enums';
import { IsEnum, IsInt, IsOptional } from 'class-validator';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsPrimitive } from '../shared/decorator/decorators';

export class CreateMeasurementDto {
  @IsOptional()
  @IsInt()
  @ApiPropertyOptional()
  timestamp: number;

  @IsOptional()
  @IsEnum(Precision)
  @ApiPropertyOptional({ enum: Precision })
  precision: Precision;

  @ApiProperty({
    description:
      'Key/value pairs; values can be of type string, boolean or number.',
    type: Map,
  })
  @IsPrimitive()
  datapoints: Map<string, string | boolean | number>;
}

What I get in the SwaggerUi schema section is this:

CreateMeasurementDto{
    timestamp   number
    precision   string
                Enum:[ s, ms, u, ns ]
    datapoints* Map {
                }
}

I want at least give an example or describe an element of the map. Both would be awesome.
The map is allowed to have strings as keys, while values can be string, boolean or number.

Here is a possible payload, that would be accepted:

{
    "precision": "s",
    "datapoints": {
            "voltage": 123.6456,
            "current": 123
        }
}
like image 387
JWo Avatar asked Dec 05 '19 11:12

JWo


1 Answers

With the latest version of nestjs/swagger which is version 4, you can define Raw Definitions Swagger Documentations

@ApiProperty({
  type: 'object',
  additionalProperties: {
    oneOf: [
      { type: 'string' },
      { type: 'number' },
      { type: 'boolean' }
    ]
  }
})
datapoints: Map<string, string | boolean | number>;
like image 77
Chau Tran Avatar answered Oct 19 '22 09:10

Chau Tran