Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow enum to use a function #2786

Closed
1 task done
slukes opened this issue Jan 22, 2024 · 4 comments
Closed
1 task done

Allow enum to use a function #2786

slukes opened this issue Jan 22, 2024 · 4 comments
Labels

Comments

@slukes
Copy link
Contributor

slukes commented Jan 22, 2024

Is there an existing issue that is already proposing this?

  • 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 slukes added the feature label Jan 22, 2024
@kamilmysliwiec
Copy link
Member

Would you like to create a PR for this issue?

@eyeamkd
Copy link

eyeamkd commented Feb 23, 2024

@kamilmysliwiec I created a PR for this #2852

@slukes
Copy link
Contributor Author

slukes commented Apr 29, 2024

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

@kamilmysliwiec
Copy link
Member

Let's track this here #2935

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants