我是 GraphQL 的新手。我正在遵循互联网上的几个指南,以便“创建”一个使用Apollo Server Express GraphQL MongoDB的小应用程序。
我在编译时从GraphQL获得:
错误:只能有一个名为“User”的类型。
错误:只能有一个名为“查询”的类型。
我像这样构建我的代码:
到目前为止,我的代码如下所示:
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
];
然后在我的索引中.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}`)
});
我做错了什么?
当遵循深度模块化模式时,您希望每个类型定义都在自己的文件中,并且每个解析器集都在自己的文件中,您希望使用扩展
关键字并创建“空”定义。
假设您在不同的文件中有< code>root和< code>user类型定义,那么将它们放在一起的索引文件应该如下所示:
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
}
进行空的< code >查询。然后在最后添加用户和根用户。
在您的用户文件中,您会希望这样:
extend type Query {
getUsers: [User]
}
所以< code>extend关键字是扩展您在索引文件中创建的空查询。
你可以在这里阅读更多关于模块化的信息https://blog.apollographql.com/modularizing-your-graphql-schema-code-d7f71d5ed5f2