nestjsnestjs-swagger

Nestjs IsEnum dto validation and swagger


This is working fine:

    import { IsIn } from 'class-validator';
    import { ApiProperty } from '@nestjs/swagger';

    export class createEventDto {
      @IsIn([0, 1, 2, 3, 4, 5])
      @ApiProperty({
        description: 'description of the severity property',
      })
      severity: number;
    }

and looks like this in swagger: swagger-number

I am trying to understand how can I change severity type to enum, what I've tried:

export enum Severity {
  Critical = 1,
  Major = 2,
  Minor = 3,
  Warning = 2,
  Info = 1,
  Clear = 0,
}
    import { IsEnum } from 'class-validator';
    import { ApiProperty } from '@nestjs/swagger';
    import { Severity} from '../enums/severities';

    export class createEventDto {
      @IsEnum(Severity)
      @ApiProperty({
        description: 'description of the severity property',
      })
      severity: Severity;
    }

Although it is working, swagger looks a bit off (example is incorrect and the description for severity in schema becomes nested in brackets: swagger-enum


Solution

  • If you want to express an enum on SwaggerUI, you need to provide enum property to ApiProperty decorator

     import { IsEnum } from 'class-validator';
     import { ApiProperty } from '@nestjs/swagger';
     import { Severity} from '../enums/severities';
    
     export class createEventDto {
       @IsEnum(Severity)
       @ApiProperty({
         description: 'description of the severity property',
         enum: Severity
       })
       severity: Severity;
     }