【问题标题】:graphql enum not defined in schemagraphql 枚举未在模式中定义
【发布时间】:2019-10-01 21:21:38
【问题描述】:

我目前正在学习 GraphQL,但偶然发现了这个错误。如何在仍然使用 GraphQLEnumType 对象的同时修复它。

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}`);
});

以下是错误:

/home/jonas/Projects/javascript-questions-flow4b/backend/node_modules/graphql-tools/dist/generate/addResolveFunctionsToSchema.js:53 throw new _1.SchemaError(typeName + "." + fieldName + " 已在解析器中定义,但枚举不在模式中"); ^

错误:Bonus.name 已在解析器中定义,但枚举不在架构中

【问题讨论】:

    标签: javascript node.js enums graphql


    【解决方案1】:

    如果您使用typeDefsresolvers 配置ApolloServer,则不能使用GraphQLEnumType。相反,如果您想为枚举值提供自定义值,请将适当的对象作为resolvers 的一部分传递,如the docs 所示。

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

    请注意,如果您想在内部将枚举值映射到其名称以外的其他内容,则只需要执行此操作。 BIG 将映射到 "BIG"SMALL 将映射到 "SMALL" 默认情况下,所以如果这就是你所需要的,根本不要在解析器中包含 Bonus

    【讨论】:

    • 谢谢,我想我需要做更多的阅读才能完全理解这个答案:)
    • 如果这不能完全回答您的问题,我很乐意提供更多详细信息。如果您正在使用 Apollo 构建服务器,我建议您坚持使用他们的 extensive documentation。虽然 Apollo 在后台使用 GraphQL.js,但大多数实际 GraphQL.js 文档在您使用 Apollo 时并不相关。
    【解决方案2】:

    如果您使用 typeDefs 和解析器配置 ApolloServer,您实际上可以使用 GraphQLEnumType。

    在 typeDefs 对象中将 BonusType 定义为标量:

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

    现在,无论何时添加对 BonusType 对象的查询,您都会得到以下结果: 1. BonusType 枚举的名称。 2. BonusType 枚举值。

    更多信息请见https://spectrum.chat/apollo/apollo-server/how-to-use-custom-enums~376c8da8-19a5-4338-9bee-4cba7a036d8f

    【讨论】:

      猜你喜欢
      • 2022-01-03
      • 1970-01-01
      • 1970-01-01
      • 2019-10-19
      • 1970-01-01
      • 2016-07-01
      • 2015-01-18
      • 2021-04-07
      • 2021-12-23
      相关资源
      最近更新 更多