nestjs / swagger

OpenAPI (Swagger) module for Nest framework (node.js) :earth_americas:
https://nestjs.com
MIT License
1.68k stars 464 forks source link

Allow enum to use a function #2786

Closed slukes closed 4 months ago

slukes commented 8 months ago

Is there an existing issue that is already proposing this?

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.

kamilmysliwiec commented 8 months ago

Would you like to create a PR for this issue?

eyeamkd commented 7 months ago

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

slukes commented 4 months ago

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

kamilmysliwiec commented 4 months ago

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