How can I return enum options in GraphQL?

2.2k views Asked by At

I have an enum in a schema like this:

enum Classification {
  A
  B
  C
  D
}

And the following query:

type Query {
  listClasification: Clasification
}

Ant the resolver on the JS code is the following:

const classification = {
  A: 'A',
  B: 'B',
  C: 'C',
  D: 'D'
};

const resolvers = {
  Query: {
    listClasification: () => {return classification}
  },
};

But when I execute the following query:

{
  listClasification 
}

I got the following error:

"message": "Enum "Classification" cannot represent value: { A: "A", B: "B", C: "C", D: "D" }",

Then, how can solve this error, and return all classifications in a query?

Thanks

1

There are 1 answers

0
Caerbannog On

You have two problems.

The first problem is in your schema: listClasification probably needs to return a list of values. The closest thing in GraphQL is an array. Here is the fixed schema with an array of Clasification:

type Query {
  listClasification: [Clasification]
}

The second problem is in your resolver. You want to receive data like ['A', 'B', 'C', 'D'] (an array), so that's what your resolver should return. You are currently returning an object, not an array. If you want to convert between your classification object and an array, here is the fixed resolver.

const resolvers = {
  Query: {
    listClasification: () => { return Object.keys(classification) }
  },
};

Note that it could be simpler if your just defined classification = ['A', 'B', 'C', 'D'].