我有一个情况,我有模式,reolvers坐在各种不同的文件中。我已将架构和解析器导入服务器.js该文件负责创建阿波罗服务器。目前,一组解析器和查询,我正在导入,另一组查询和解析器已经在服务器.js文件中。
这是服务器.js文件的内容。
import "graphql-import-node";
import { ApolloServer, gql } from "apollo-server";
import { makeExecutableSchema } from "graphql-tools";
import merge from "lodash/merge";
import GithubFetchHelper from "./github/GithubFetchHelper";
import {
resolvers as GithubResolvers,
typeDefs as GithubTypeDef
} from "./github";
/**
* Error Handler. Provides full stack - remove for production
*/
const books = [
{
title: "Harry Potter and the Chamber of Secrets",
author: "J.K. Rowling"
},
{
title: "Jurassic Park",
author: "Michael Crichton"
}
];
const typeDefs = gql`
# Comments in GraphQL are defined with the hash (#) symbol.
# This "Book" type can be used in other type declarations.
type Book {
title: String
author: String
}
# The "Query" type is the root of all GraphQL queries.
# (A "Mutation" type will be covered later on.)
type Query {
books: [Book]
}
`;
const resolvers = {
Query: {
books: () => books
}
};
// typeDefs: [
// project.typeDefs,
// task.typeDefs,
// search.typeDefs
// ].join(' '),
// resolvers: merge({}, project.resolvers, task.resolvers, search.resolvers),
// context: {
// models: {
// project: project.model,
// task: task.model
// },
// loaders: loaders()
// }
const server = new ApolloServer({
typeDefs: [typeDefs, GithubTypeDef],
resolvers: merge({}, resolvers, GithubResolvers),
dataSources: () => {
return {
gitHubApi: new GithubFetchHelper()
};
}
});
server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});
export default server;
现在,当我运行服务器时,出现以下错误。任何帮助,不胜感激。
Error: Type "Query" was defined more than once.
我的尝试 我已经参考了 apollo 文档的数据源以及使用 graphql-tools 中的 gql 合并多个模式和解析器。但是我没有在他们也使用数据源的地方获得任何 gql 的实现。
任何帮助,不胜感激。
注意:我对 Graphql 很陌生
从代码中,您将 2 个 typedef 作为数组传递,这可能是您收到错误的原因。您需要将架构拼接在一起。看:
- https://www.graphql-tools.com/docs/schema-stitching/stitch-combining-schemas
- https://blog.apollographql.com/the-next-generation-of-schema-stitching-2716b3b259c0
假设您在主 js 文件中导入了模式和解析器,您可以按以下方式进行拼接。您可以使用require-graphql-file
模块来简化 graphQL 模式导入。
import {merge } from 'lodash'
import requireGraphQLFile from 'require-graphql-file';
import {makeExecutableSchema } from 'apollo-server';
import resolver1 from './resolvers/resolver1';
import resolver2 from './resolvers/resolver2';
import resolver3 from './resolvers/resolver3';
const schema1= requireGraphQLFile('./schema/schema1');
const schema2= requireGraphQLFile('./schema/schema2');
const schema3= requireGraphQLFile('./schema/schema3');
const resolvers = merge(resolver1, resolver2, resolver3)
const typeDef = gql `
type Query {
getData(filters:Filter,limit:Int,offset:Int):Result
}`;
const schema = makeExecutableSchema({
typeDefs: [typeDef, schema1,schema2, schema3],
resolvers
});
const server = new ApolloServer({
schema
});