8

I cannot find anywhere in the graphql-tools documentation how one should go about utilizing enum types in schemas that are fed to makeExecutableSchema. Anyone have a clue how this done?

Example code:

enum Color {
  RED
  GREEN
  BLUE
}

type Car {
  color: Color!
}

What would the resolver for Color look like?

Dallas
  • 888
  • 3
  • 10
  • 24

2 Answers2

11

You wouldn't write a resolver for Color. Here's a simple, runnable example:

const bodyParser = require('body-parser');
const { graphqlExpress, graphiqlExpress } = require('graphql-server-express');
const { makeExecutableSchema } = require('graphql-tools');
const app = require('express')();

const carsData = [
  {color: 'RED'},
  {color: 'GREEN'},
  {color: 'BLUE'},
];

const typeDefs = `
  enum Color {
    RED
    GREEN
    BLUE
  }
  type Car {
    color: Color!
  }
  type Query {
    cars: [Car!]!
  }
`;

const resolvers = {
  Query: {
    cars: () => carsData,
  }
};

const schema = makeExecutableSchema({
  typeDefs,
  resolvers,
});

app.use('/graphql', bodyParser.json(), graphqlExpress({ schema }));
app.use('/graphiql', graphiqlExpress({ endpointURL: '/graphql' }));

app.listen(3000);

Run a cars query ({cars {color}}) in GraphiQL and you will see a color returned for each car in our data. Now, change one of the values in the data (not the Enum definition) to a color you didn't define, like PINK. Run the query again and you will see an error message like:

"Expected a value of type \"Color\" but received: PINK"

This works with resolvers too, so if I override the data by adding a resolver for Car like this:

Car: {
  color: () => 'RED'
}

The query will show all the cars with RED as their color. If you change the value returned by the resolver to BLACK, the query will error out again.

Enums are just a way of enforcing that whatever value a particular field resolves to is within the set of values you define.

mmell
  • 2,448
  • 1
  • 24
  • 16
Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183
  • OK, so this simply works out of the box. It was not knowing how the values of the enums are determined that had me thinking I had to set up a resolver for these guys, then I didn't see anything in the docs about it. Thanks for the direction! – Dallas Jul 13 '17 at 03:57
7

By default, the enum is represented with the same string : enum Color { RED } is 'RED'. You can override this by adding a resolver to the enum:

Color: {
  RED: '#ff0000',
  GREEN: '#00ff00'
},
Query {...

More info: https://www.apollographql.com/docs/graphql-tools/scalars.html#internal-values

thesecretmaster
  • 1,950
  • 1
  • 27
  • 39
azazdeaz
  • 113
  • 1
  • 6