Tom93
Tom93

Reputation: 63

NestJS - Swagger - Show all enum values

I would like to see all enums value about my dto's property in the body section of swagger UI.

I put this @ApiQuery decorator in my code:

@ApiQuery({
  name: 'name',
  enum: ENUM_NAME,
  isArray: true,
})
@Post()
async name(...):Promise<...> {...}

But this is used with @Query decorator to let the swagger's filter work. (Find in NestJS Swagger Doc).

So i did not put @Query in my code as you can see, because i want the enum's value in my dto.

This is the result

But it did not like this solution. it's a workaround.

There is a better way to achieve this result?

Upvotes: 6

Views: 32724

Answers (3)

Sabin Bogati
Sabin Bogati

Reputation: 741

This is how is resolved this:

  @IsNotEmpty()
  @ApiProperty({
    enum: DiningAreaType,
    enumName: 'DiningAreaType',
  })
  @IsArray()
  @IsEnum(DiningAreaType, { each: true })
  diningArea: DiningAreaType[];

Upvotes: 0

Ali RaZa
Ali RaZa

Reputation: 11

you can try this way

@ApiProperty({
description: "List of all events",
isArray: true,
enum: TriggerEventType,
example: Object.keys(TriggerEventType),
})

Upvotes: 1

Jboucly
Jboucly

Reputation: 855

It is not possible in the body section of swagger to do as for the query section, but you can do like this:

// app.controller.ts

@Post()
public async name(@Body() dto: NameDto): Promise<void> {}

// name.dto.ts

// This is enum for demo
enum Demo {
    DEMO_1 = 'DEMO_1',
    DEMO_2 = 'DEMO_2',
}

export class NameDto {
    @ApiProperty({
        enum: Demo,
        isArray: true,
        example: [Demo.DEMO_1, Demo.DEMO_1],
    })
    public name: Demo[];
}

And the result => Swagger

Or if you don't want dto used

// app.controller.ts

@Post()
@ApiBody({
    schema: {
       type: 'object',
         properties: {
            name: {
              type: 'array',
              items: {
                 enum: [Demo.DEMO_1, Demo.DEMO_2],
                 example: [Demo.DEMO_1, Demo.DEMO_2],
              },
            },
        },
    },
})
public async name(@Body() dto: any): Promise<void> {}

Upvotes: 15

Related Questions