Enums
An enum (enumeration) is a scalar-like type restricted to a fixed set of named values. Use one whenever a field or argument has a known list of options: an order status, a sort direction, a size. Compared with a plain String, enums are validated by the engine, documented in the schema and autocompleted by tools.
Defining and using an enum
enum OrderStatus {
PENDING
SHIPPED
DELIVERED
CANCELLED
}By convention enum values are ALL_CAPS. In queries they're written as bare names, without quotes:
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`
enum OrderStatus { PENDING SHIPPED DELIVERED CANCELLED }
type Order { id: ID!, total: Int!, status: OrderStatus! }
type Query { orders(status: OrderStatus): [Order!]! }
`);
const orders = [
{ id: 'A1', total: 1200, status: 'SHIPPED' },
{ id: 'A2', total: 450, status: 'PENDING' },
{ id: 'A3', total: 3100, status: 'SHIPPED' },
];
const rootValue = {
orders: ({ status }) => (status ? orders.filter((o) => o.status === status) : orders),
};
const result = await graphql({
schema,
rootValue,
source: '{ orders(status: SHIPPED) { id status } }',
});
console.log(JSON.stringify(result.data));{"orders":[{"id":"A1","status":"SHIPPED"},{"id":"A3","status":"SHIPPED"}]}
With buildSchema, an enum value's internal representation is just its name as a string, so resolvers compare against 'SHIPPED'.
Invalid values are rejected
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`
enum Size { SMALL MEDIUM LARGE }
type Query { shirt(size: Size!): String, cupSize: Size }
`);
const rootValue = { shirt: ({ size }) => `T-shirt in ${size}`, cupSize: 'HUGE' };
for (const source of [
'{ shirt(size: MEDIUM) }',
'{ shirt(size: "MEDIUM") }', // quoted: that's a string
'{ shirt(size: XL) }',
'{ cupSize }', // bad value from the resolver
]) {
const result = await graphql({ schema, source, rootValue });
console.log(result.errors ? result.errors[0].message : JSON.stringify(result.data));
}{"shirt":"T-shirt in MEDIUM"}
Enum "Size" cannot represent non-enum value: "MEDIUM". Did you mean the enum value "MEDIUM"?
Value "XL" does not exist in "Size" enum.
Enum "Size" cannot represent value: "HUGE"
Note the difference: in the query text an enum must be a bare name, but in variables (which are JSON) it's sent as a string, e.g. {"size": "MEDIUM"}.
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`
enum Size { SMALL MEDIUM LARGE }
type Query { shirt(size: Size!): String }
`);
const result = await graphql({
schema,
source: 'query Shirt($size: Size!) { shirt(size: $size) }',
rootValue: { shirt: ({ size }) => `T-shirt in ${size}` },
variableValues: { size: 'LARGE' },
});
console.log(JSON.stringify(result.data));{"shirt":"T-shirt in LARGE"}
Mapping to internal values
Your storage often uses different values: numbers, lowercase strings. With the code-first API (GraphQLEnumType) each public name can map to any internal value. The engine converts in both directions:
import { graphql, GraphQLSchema, GraphQLObjectType, GraphQLEnumType, GraphQLString, GraphQLList } from 'graphql';
const Priority = new GraphQLEnumType({
name: 'Priority',
values: {
LOW: { value: 1 },
NORMAL: { value: 2 },
URGENT: { value: 3, description: 'Handle today' },
},
});
const tickets = [
{ title: 'Fix login', priority: 3 }, // stored as numbers
{ title: 'Update docs', priority: 1 },
{ title: 'Refactor CSS', priority: 2 },
];
const Ticket = new GraphQLObjectType({
name: 'Ticket',
fields: { title: { type: GraphQLString }, priority: { type: Priority } },
});
const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'Query',
fields: {
tickets: {
type: new GraphQLList(Ticket),
args: { atLeast: { type: Priority } },
resolve: (_root, { atLeast }) => {
console.log('resolver received atLeast =', atLeast);
return tickets.filter((t) => t.priority >= atLeast);
},
},
},
}),
});
const result = await graphql({ schema, source: '{ tickets(atLeast: NORMAL) { title priority } }' });
console.log(JSON.stringify(result.data));resolver received atLeast = 2
{"tickets":[{"title":"Fix login","priority":"URGENT"},{"title":"Refactor CSS","priority":"NORMAL"}]}
The client wrote NORMAL, the resolver received 2, and the stored 3 and 2 went back out as URGENT and NORMAL. You'll learn the full code-first API in the Resolvers lesson.
Deprecating a value
Enum values can be deprecated like fields:
enum Plan {
FREE
PRO
TEAM @deprecated(reason: "Merged into PRO.")
}Warning: Adding a new enum value can break clients that
switchon the value without a default branch. Treat enums in outputs as "may grow" and always handle unknown values in client code.
Test yourself
How do you pass the enum value SHIPPED as a literal argument in a query?
status: "SHIPPED"status: SHIPPEDstatus: 'SHIPPED'status: OrderStatus.SHIPPED
How is an enum value sent inside the JSON variables object?
- As a bare name
- As a string such as
"LARGE" - As its index number
- Enums can't be variables
What does GraphQLEnumType let you do that buildSchema alone doesn't?
- Use lowercase names
- Map public names to different internal values
- Create more than 10 values
- Skip validation