簡體   English   中英

架構中未定義 graphql 枚舉

[英]graphql enum not defined in schema

我目前正在學習 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 已在解析器中定義,但枚舉不在架構中

如果您使用typeDefsresolvers配置 ApolloServer,則不能使用GraphQLEnumType 相反,如果您想為枚舉值提供自定義值,請將適當的對象作為resolvers一部分傳入,如文檔中所示。

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

請注意,僅當您想在內部將枚舉值映射到名稱以外的內容時,才需要執行此操作。 默認情況下, BIG將映射到"BIG"SMALL將默認映射到"SMALL" ,因此,如果您只需要這些,根本不要在解析器中包含Bonus

如果您使用 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM