We want a user to have one of two possible roles:
Currently, a client could potentially set the role of the user to any arbitrary string, like
CHICKEN, which would obviously not make sense in our app.
We need a mechanism to establish a contract that the user.role can only be set to a pre-approved value.
Enums are a way to create a list of pre-approved values for a certain type. In our case, we want to define an enum named
Role that contains two possible values:
This mechanism tells our program that a
Role type can only ever have the value
How to use enums to improve our role-based permission system
Role enum in the top level of the schema.
Role enum as the return type for the
role field on the
User type (in schema/user.js).
Role enum as the argument type for our
This has the added benefit of giving us autocomplete in GraphQL Playground when setting the user’s role with this mutation:
Sweet! Less room for error.