3

https://launchpad.graphql.com/9qvqz3v5r

Here is my example graphQL Schema. i am trying to use enum type. How do i get enum values from backend and give it into schema?

// Construct a schema, using GraphQL schema language
const typeDefs = `
  type User {
        userId: Int
        firstName: String
        lastName: String
        pincode:String
        state:String
        country:String
  }
  type Query {
    hello: String
    user: User
  }
  type CreateUserLoad {
    user: User 
  }
  enum Role {
        writer
        reader
        author
        admin
        superAdmin
  }
  type Mutation{
        createUser(firstName: String, lastName: String, role: Role): User
  }
`;

I want to populate enum Role value from dynamic variable as

const roleData = ['writer','reader','author','admin','superAdmin'];

Can anyone help me?

1
  • Did you find the solution? the accepted answer is not working for me. As my schema is defined in .graphql file, and I can't inject external variables there. Still looking the solution Commented Dec 21, 2020 at 17:13

3 Answers 3

2

You can simply use string interpolation:

// Construct a schema, using GraphQL schema language
const typeDefs = `
  type User {
        userId: Int
        firstName: String
        lastName: String
        pincode:String
        state:String
        country:String
  }
  type Query {
    hello: String
    user: User
  }
  type CreateUserLoad {
    user: User 
  }
  enum Role { ${roles.join(' ')} }
  type Mutation{
        createUser(firstName: String, lastName: String, role: Role): User
  }
`;

In fact, on every incoming grahpql query you have to pass the parsed schema to the graphql server, so you can even change it for every request. In that case, it would be better to change the object representation that the schema parsing returned.

For creating enum types directly, say you have an array of values userRoles and want a RolesEnum type, then you can create it like so:

const roleValues = {}
for (const value of userRoles) {
    roleValues[value] = {value}
}
const RolesEnum = new GraphQLEnumType({
    name: 'UserRoles',
    values: roleValues,
})

you can then assign that directly as a type in your schema.

Sign up to request clarification or add additional context in comments.

6 Comments

"In fact, on every incoming grahpql query you have to pass the parsed schema to the graphql server, so you can even change it for every request." You can't seriously be suggesting that he parses the scheme for each request?
After the schema is parsed you have the object representation, which you can change.
You are right, but that's not what your example suggests. If you wish to alter your answer with this new example I can replace my -1 with +1.
@zoran404 something like that?
@w00t Well you didn't provide an example of how to set enum values in the schema object, so I don't see your answer as useful, but I'll remove the -1. I get why you wouldn't want to bother with writing an example for this, since you'd need to generate the new astNode for each enum value or use the parser to generate it. And both of the solutions might take a while to figure out.
|
2

If your enum values are loaded from a database or any other back-end source, or if the enum list is dynamic, then you can't have a static enum definition in your schema.

The biggest problem with setting enums dynamically is that your schema is meant to be a contract between back-end and front-end and is not suppose to be altered.

If you are going to use your role as an arbitrary string then define it as such!

type Mutation {
  createUser(firstName: String, lastName: String, role: String): User
}

The only difference here would be that your resolver will have to check if the role exists, which is what graphql previously did for you when you were using an enum.

Alternatively

If the role is used on a lot of queries / mutations, you can define a scalar Role and in the resolved for the scalar you can check if the role exists and simply throw an error if it doesn't.

In this case your mutation would look the same as if you had a dynamic enum Role, but you will not need to alter the schema at all.

type Mutation {
  createUser(firstName: String, lastName: String, role: Role): User
}

Comments

1

To add dynamic enums along with documentation string using string interpolation.

Example: I have a list of countries and their ISO2 Codes

const countryData = [
   {name:'India', code: 'IN'},
   {name:'Afghanistan', code: 'AF'},
   {name:'Algeria', code: 'DZ'},
   {name: 'Ireland', code: 'IE'
];

const countryCodes = countryData.flatMap(country => [
  `"${country.name}"`,
  country.code
]);

Without using Array.join()


enum CountryCode { ${countryCodes} }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.