Should I expect enum types to resolve automatically or do the types only exist to limit options?
Given a GraphQL Schema of the following:
type Job {
description: String!
status: Status!
}
enum Status {
PENDING_REVIEW
PENDING_APPROVAL
APPROVED
}
and a query that looks like:
query job {
description
status
}
If my database returned the following:
{ "description": "Some irrelevant job description", "status": 1 }
I would expect GraphQL to return:
{ "description": "Some irrelevant job description", "status": "PENDING_APPROVAL" }
Have I set something up incorrectly, or is this expected behaviour that will require me to write a resolver for status
const getQuestionStatus = ({ status }) => ['PENDING_REVIEW', 'PENDING_APPROVAL', 'APPROVED'][status];
In GraphQL.js, each enum value in an Enum Type may have an associated value with it. Setting this value is optional; it defaults to the string representation of the value's name. That is, for an enum like:
enum ExampleEnum {
FOO
BAR
}
by default, the value for FOO
will be "FOO"
. If you're using graphql-tools
to build your schema (or using apollo-server
, which uses graphql-tools
under the hood`) we can pass in the values for an Enum type right in our resolvers:
const resolvers = {
Query: {
example: () => 11, // field with ExampleEnum type
},
ExampleEnum: {
FOO: 11,
BAR: 23,
},
}
Once we've done that, we can return the defined value in our resolver and it will be serialized into the appropriate Enum value. Note: the same is true of enums that are used as arguments -- if FOO
is passed in as an argument, the resolver will actually receive a value of 11
.
Not providing any values is equivalent to doing:
ExampleEnum: {
FOO: 'FOO',
BAR: 'BAR',
}
It's also worthwhile to note that providing values has no impact on how the enum values are shown in the response. When the execution result is serialized into JSON, enum values are always shown as string values that match the names of the enum values (i.e. "FOO"
and "BAR"
in our example).
What about vanilla GraphQL.js?
Values for enum values can also be provided if you define your schema programatically. Here's an equivalent of the above example:
const ExampleEnumType = new GraphQLEnumType({
name: 'ExampleEnum',
values: {
FOO: {
value: 11,
},
BAR: {
value: 23,
},
},
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With