【问题标题】:Apollo Server - GraphQL Error: There can be only one type named "Query"Apollo Server - GraphQL 错误:只能有一种名为“查询”的类型
【发布时间】:2019-08-31 05:39:32
【问题描述】:

我是 GraphQL 的新手。为了“创建”一个使用 Apollo Server + Express + GraphQL + MongoDB 的小应用程序,我正在遵循 Internet 上的几个指南。

  • 我试图复制this YT guide(他在 typeDefs 文件夹中创建了 root.js 文件)。
  • This one 用于测试目的。
  • this one 确保我的文件夹结构正确。

我在编译时从 GraphQL 获取:

错误:只能有一种名为“用户”的类型。

错误:只能有一种名为“查询”的类型。

我的代码结构如下:

  • 配置
  • 型号
  • 解析器
    • index.js
    • user.js
  • 类型定义
    • index.js
    • root.js
    • user.js
  • index.js

到目前为止,我的代码如下所示:

typeDefs/user.js

import { gql } from 'apollo-server-express';

const user = gql`
    type User {
        id: ID!
        name: String
        email: String
        password: String
    }

    type Query {
        getUsers: [User]
    }

    type Mutation {
        addUser(name: String!, email: String!, password: String!): User
    }
`;

export default user;

typeDefs/root.js

import { gql } from 'apollo-server-express';

export default gql`
    extend type Query {
        _: String
    }

    type User {
        _: String
    }
`;

typeDefs/index.js

import root from './root';
import user from './user';

export default [
  root,
  user
];

然后在我的 index.js 中:

import express  from 'express';
import  { ApolloServer, gql } from 'apollo-server-express';

import typeDefs  from './typeDefs';
import resolvers from './resolvers';

const server = new ApolloServer({ typeDefs, resolvers });
const app = express();
server.applyMiddleware({ app });

app.disable('x-powered-by');

app.listen({ port: 4000 }, () => {
  console.log(`Server running at http://localhost:4000${server.graphqlPath}`)
});

我做错了什么?

【问题讨论】:

  • 添加两个用户定义,一个在typeDefs/root.js:,另一个在typeDefs/user.js:。把根去掉就够了。
  • @Striped,好吧...我只收到一个错误。是的,正如预期的那样。但是,如果在 typeDefs/index.js 中组合的多个文件上定义了多个查询怎么办?
  • 您的typeDefs 没问题,只要您在root.js 中的两种类型都有extend 关键字。我在本地运行代码,它运行良好。您是否仍然看到关于 Query 被多次定义的错误?如果是这样,您运行的是哪个版本的 apollo-server-express
  • @DanielRearden 我在 typeDefs/user.js 上添加了 extend type Queryextend type User,现在似乎可以工作了。做出你的答案。

标签: javascript node.js express graphql apollo-server


【解决方案1】:

当遵循深度模块化模式时,您希望将每个类型定义放在自己的文件中,并将每组解析器放在自己的文件中,您希望使用 extend 关键字并创建“空”定义。

假设您在单独的文件中有 rootuser 类型定义,那么将它们放在一起的索引文件应该如下所示:

const user = require('./user');
const root= require('./root');
const typeDefs = gql`
    type Query{
        _empty: String
    }
    type Mutation {
        _empty: String
    }
    ${user}
    ${root}
`;

module.exports = typeDefs;

你正在使用

    type Query{
        _empty: String
    }

创建一个空的Query。然后你在最后添加你的用户和根。

在你的用户文件中,你会想要这个:

    extend type Query {
        getUsers: [User]
    }

所以extend 关键字是您扩展您在索引文件中创建的空查询。

您可以在此处阅读更多关于模块化的信息https://blog.apollographql.com/modularizing-your-graphql-schema-code-d7f71d5ed5f2

【讨论】:

    猜你喜欢
    • 2020-03-11
    • 2019-11-02
    • 2020-04-23
    • 2018-10-16
    • 2019-01-17
    • 2020-11-27
    • 2021-06-30
    • 2018-10-19
    • 2020-10-18
    相关资源
    最近更新 更多