swagger
swagger copied to clipboard
Allow enum to use a function
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.
Would you like to create a PR for this issue?
@kamilmysliwiec I created a PR for this https://github.com/nestjs/swagger/pull/2852
Hello @kamilmysliwiec pushed my own PR for this since @eyeamkd seems to have not had the time. Let me know.
Let's track this here https://github.com/nestjs/swagger/pull/2935