DEV Community

Cover image for How to generate dynamic ENUM type in GraphQL from DataBase using NestJS, MongoDB

How to generate dynamic ENUM type in GraphQL from DataBase using NestJS, MongoDB

Never stop learning
・2 min read

In this article I am gonna show how to generate Enum type of GraphQL by fetching data from Database in NestJS, I am using MongoDB as my Database with Mongoose, you can use any database.

I am taking example of User, in which I am storing user’s firstName, lastName and role, for role I want to make an Enum which will be dynamically generated from the roles available in the role table in Database. Also, I am dynamically resolving the selected role to the corresponding id of that role, so that way I can store the id of role in my user record.

First of all I’ll fetch all the record of role table

Then I’ll extract all the name field of role in roleNames variable,

In this filter and map function tweaks I have returned an array containing string of all roles.

As you can see I have discarded ‘ADMIN’ as I don’t want that user can select ‘ADMIN’ role by his own, to add admin user we might want to use seed data.

Now I will generate Enum string,

By joining all the roleNames with ‘ ’(single space) we will have Enum type for UserRole ready, but its just string we didn’t put it in actual GraphQL file, will do it in a short time, before that let us resolve that roles to its corresponding id so that I can easily store it in user table.

As you can see, I am making an object of UserRole which has property as role name and value as role id,

So, every role will have its corresponding role id.

Now we have generated Enum and its resolver, we have to put it in GraphQL, for that we have to put both of them in GraphQL options, which is executed every time you run the project.

So that’s it you have successfully generated Enum type in GraphQL which is dynamically generated based on data in database.

Let us have a look at what GraphQL playground looks like,

Alt Text

As I have only 2 roles ‘STUDENT’ and ‘TEACHER’ in my DB, GraphQL shows me those 2 as suggestion in role field.

Alt Text

You can go to my GitHub to get whole code for this NestJS project.

Thank you.

Happy coding!

Discussion (0)