【问题标题】:Create Apollo-Server with Federated schema使用联合模式创建 Apollo-Server
【发布时间】:2021-11-09 11:22:54
【问题描述】:

我正在尝试使用从 GraphQL 文件加载的 TypeDefs 联合模式创建 Apollo-Server。但是,我收到此错误

Argument of type 'GraphQLSchema' is not assignable to parameter of type 'string | TemplateStringsArray'.

我相信我从文件中加载架构时使用了错误的函数loadSchema。 如何从文件中加载具有正确类型的架构以将其作为 TypeDef 提供给联合架构?

import { buildSubgraphSchema } from '@apollo/federation';
import { CodeFileLoader } from '@graphql-tools/code-file-loader';
import { loadSchema } from '@graphql-tools/load';
import { ApolloServer, gql } from 'apollo-server';
...

const typeDefs = await loadSchema(`${__dirname}/auth.graphql`, {
  loaders: [new CodeFileLoader()],
});

const server = new ApolloServer({
 schema: buildSubgraphSchema([
     {
        typeDefs: gql(typeDefs),    // Error here `typeDefs`
        resolvers,
     }
  ]),
})

【问题讨论】:

    标签: typescript graphql apollo-server graphql-tools


    【解决方案1】:

    我也在从文件中加载子图架构,并这样做:

    import { parse } from "graphql";
    import { ApolloGateway } from "@apollo/gateway";
    import * as fs from "fs";
    
    const sdlStringFromFile = fs.readFileSync(
            `${__dirname}/auth.graphql`
        );
    
    new ApolloGateway({
      localServiceList: [{
        name: "ServiceA",
        url: "https://servicea.com/graphql",
        typeDefs: parse(sdlStringFromFile)
      }]
    })
    

    【讨论】:

    • 这种方式是上传子图的最佳做法吗?
    • @Hazemalabiad 如果您要向 Apollo 询问最佳实践,我希望他们的回答是使用 Apollo Managed Federation 并让 Apollo 服务器在运行时从注册表加载架构。
    • 如果我想将联合的单一、联合、组合的模式打印或输出到单个文件中呢?
    【解决方案2】:

    您不需要使用gql 函数。架构已被解析。

    import { buildSubgraphSchema } from '@apollo/federation';
    import { CodeFileLoader } from '@graphql-tools/code-file-loader';
    import { loadSchema } from '@graphql-tools/load';
    import { ApolloServer } from 'apollo-server';
    ...
    
    const typeDefs = await loadSchema(`${__dirname}/auth.graphql`, {
      loaders: [new CodeFileLoader()],
    });
    
    const server = new ApolloServer({
     schema: buildSubgraphSchema([
         {
            typeDefs: typeDefs,
            resolvers,
         }
      ]),
    })
    

    【讨论】:

    • 当我删除 gql 函数时,我得到另一个错误 Type 'GraphQLSchema' is missing the following properties from type 'DocumentNode': kind, definitionsts(2739)
    • 我相信buildSubgraphSchema 期望typeDefsDocumentNode 类型。所以,我猜我们要么需要在加载时使用正确的函数,要么将graphqlschema转换为documentnode
    猜你喜欢
    • 2020-12-21
    • 2020-04-04
    • 2019-12-28
    • 2019-05-10
    • 2019-03-01
    • 2022-07-11
    • 1970-01-01
    • 2021-01-09
    • 1970-01-01
    相关资源
    最近更新 更多