我们如何通过apollo-server模块在ApolloServer中传递数据源以及合并的graphql模式和解析器?

时间:2019-01-02 15:46:37

标签: typescript graphql apollo apollo-client apollo-server

我遇到的情况是,我有模式,而解决方案位于不同的文件中。我已将架构和解析器导入到负责创建apollo服务器的server.js文件中。目前,我正在导入一组解析器和查询,而server.js文件中已经存在另一组查询和解析器。

这是server.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 个答案:

答案 0 :(得分:0)

从代码中,您将2个typedef作为数组传递,这可能是您收到错误的原因。您需要将架构缝合在一起。参见:

答案 1 :(得分:0)

假设您已在主js文件中导入了架构和解析器,则可以按以下方式进行拼接。 您可以使用-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error { #ifdef DEBUG_THIS_FILE NSString* debugString = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding]; NSString* replacedWhitespace = [[debugString stringByReplacingOccurrencesOfString:@"\n" withString:@"\\n"] stringByReplacingOccurrencesOfString:@"\r" withString:@"\\r"]; XLOG( @"%@ >>> %@", peripheral, replacedWhitespace ); #endif if ( error ) { LOG( @"Could not update value for characteristic %@: %@", characteristic, error ); return; } [_inputStream characteristicDidUpdateValue]; <--- } 模块来简化graphQL模式导入。

require-graphql-file