Jonas Grønbek
Jonas Grønbek

Reputation: 2019

graphql enum not defined in schema

I am currently learning GraphQL and I have stumbled upon this error. How can I fix it while still using the GraphQLEnumType object.

const { ApolloServer, gql } = require('apollo-server');
const { GraphQLEnumType } = require('graphql');

const Bonus = new GraphQLEnumType({
    name: 'Bonus',
    values: {
        BIG: {
            value: "Big",
        },
        SMALL: {
            value: "Small",
        }
    },
});

const typeDefs = gql`

enum Bonus {
  BIG
  SMALL
}
`;

const resolvers = {
    Bonus : Bonus
}

const server = new ApolloServer({
    typeDefs,
    resolvers
});

server.listen().then(({ url }) => {
    console.log(`🚀  Server ready at ${url}`);
});

Following is the error:

/home/jonas/Projects/javascript-questions-flow4b/backend/node_modules/graphql-tools/dist/generate/addResolveFunctionsToSchema.js:53 throw new _1.SchemaError(typeName + "." + fieldName + " was defined in resolvers, but enum is not in schema"); ^

Error: Bonus.name was defined in resolvers, but enum is not in schema

Upvotes: 0

Views: 2240

Answers (2)

AutomatedOwl
AutomatedOwl

Reputation: 1089

You can actually use GraphQLEnumType if you're configuring ApolloServer using typeDefs and resolvers.

Define BonusType as scalar in your typeDefs object:

const BonusType = new GraphQLEnumType({
    name: 'Bonus',
    values: {
        BIG: {
            value: "Big",
        },
        SMALL: {
            value: "Small",
        }
    },
});

const typeDefs = gql`

scalar BonusType
`;

Now whenever adding query for BonusType object you will get as result: 1. Name of BonusType enum. 2. Value of the BonusType enum.

See https://spectrum.chat/apollo/apollo-server/how-to-use-custom-enums~376c8da8-19a5-4338-9bee-4cba7a036d8f for more info

Upvotes: 0

Daniel Rearden
Daniel Rearden

Reputation: 84687

You can't use GraphQLEnumType if you're configuring ApolloServer using typeDefs and resolvers. Instead, if you want to provide custom values for your enum values, pass in the appropriate object as part of your resolvers, as shown in the docs.

const resolvers: {
  Bonus: {
    BIG: 'Big',
    SMALL: 'Small', 
  },
}

Note that you only need to do this if you want to internally map the enum values to something other than their names. BIG will map to "BIG" and SMALL will map to "SMALL" by default, so if that's all you need, just don't include Bonus in your resolvers at all.

Upvotes: 1

Related Questions