swagger icon indicating copy to clipboard operation
swagger copied to clipboard

Allow enum to use a function

Open slukes opened this issue 1 year ago • 1 comments

Is there an existing issue that is already proposing this?

  • [X] I have searched the existing issues

Is your feature request related to a problem? Please describe it

We are using some dynamic code to find all of the possible values of an enum i.e.

export function getPossibleValues(): string[] {
  return getMetadataArgsStorage()
    .tables.filter( // some condition here)
}

However since the enum option of @ApiProperty expects a static function and not a function, the result is dependent on the order of import of modules.

Describe the solution you'd like

Modification of enum property type to

    enum?: any[] | Record<string, any> | (() => any[] | Record<string, any>)

Teachability, documentation, adoption, migration strategy

Current users => 0 impact.

New users can use function for enum values if wished.

I suggest a docs change to:


To identify an enum, we must manually set the enum property on the @ApiProperty with an array of values or a function returning an array of values.

@ApiProperty({ enum: ['Admin', 'Moderator', 'User']})
role: UserRole;

@ApiProperty({ enum: () => getAvailableUserTypes() })
role: UserRole;

⚠️ Note that functions will only be called once when the API docs are generated, so you cannot add values dynamically after application startup.

What is the motivation / use case for changing the behavior?

We want to be able to add enum values by adding an decorator on some other nestjs component in our case a typeorm entity, we do not want to have to remember to update the possible enum values.

slukes avatar Jan 22 '24 07:01 slukes

Would you like to create a PR for this issue?

kamilmysliwiec avatar Jan 23 '24 07:01 kamilmysliwiec

@kamilmysliwiec I created a PR for this https://github.com/nestjs/swagger/pull/2852

eyeamkd avatar Feb 23 '24 13:02 eyeamkd

Hello @kamilmysliwiec pushed my own PR for this since @eyeamkd seems to have not had the time. Let me know.

slukes avatar Apr 29 '24 21:04 slukes

Let's track this here https://github.com/nestjs/swagger/pull/2935

kamilmysliwiec avatar Apr 30 '24 08:04 kamilmysliwiec