Search code examples
typescriptenumsswaggernestjs

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?


Solution

  • 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> {}