gpt4 book ai didi

javascript - Apollo 服务器 - GraphQL 错误 : There can be only one type named "Query"

转载 作者:搜寻专家 更新时间:2023-11-01 00:48:25 26 4
gpt4 key购买 nike

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

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

我在编译时从 GraphQL 获取:

Error: There can be only one type named "User".

Error: There can be only one type named "Query".

我的代码结构如下:

  • 配置
  • 模特
  • 解析器
    • 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}`)
});

我做错了什么?

最佳答案

当遵循深度模块化模式时,您希望每个类型定义都在其自己的文件中,并且每组解析器都在其自己的文件中,您希望使用 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
}

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

在您的用户文件中,您需要这样:

    extend type Query {
getUsers: [User]
}

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

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

关于javascript - Apollo 服务器 - GraphQL 错误 : There can be only one type named "Query",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55601091/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com