【问题标题】:Use Apollo server as a pass through of a query from client使用 Apollo 服务器作为客户端查询的传递
【发布时间】:2020-09-26 13:10:21
【问题描述】:

我有一个用例,我有 apollo-server-express 与基于 React 的 apollo-client 一起运行。对于某些查询,我有一个外部 graphql-datasource。目前,我已将apollo-datasource-graphql 配置为我的apollo-server-express 的数据源。但是,这需要在 Apollo 中的解析器以及我的外部 graphql 系统上的解析器上重复工作。

有没有办法让我通过 Apollo 服务器将客户端中的查询传递到外部 graphql 数据源?

【问题讨论】:

  • 阿波罗联盟?
  • @xadm 这似乎有帮助,但如果我需要将查询传递给外部 Graphql 源,我不确定如何编写解析器
  • 它将外部 graphql 链接到您的服务器,所有外部资源/解析器应该在主服务器中可用 - 只需配置它(文档?),无需编写任何解析器?
  • Apollo federation 将您控制下的多个服务器链接到一个模式中。这可能不是 OP 想要的。

标签: graphql apollo-server apollo-datasource


【解决方案1】:

也许您可以从第四个解析器参数 (resolveInfo) 访问 GraphQL AST 并将其传递给 GraphQL 客户端?

这是一些原型代码:

import { print } from 'graphql/language/printer';

function forwardOperationResolver(root, args, context, resolveInfo) {
  return fetch('https://remote.host/graphql', {
    method: 'POST',
    body: JSON.stringify({
      query: print(resolveInfo.operation),
      variables: resolverInfo.variableValues,
    }),
  })
    .then(response => response.json())
    .then(response => {
      if (response.errors) {
        // Handle errors
      }
      return response.data;
    });
}

缺点:这会破坏一些通常在 GraphQL 中起作用的东西,例如部分结果和错误位置...

【讨论】:

    猜你喜欢
    • 2016-08-31
    • 2023-04-02
    • 2013-04-24
    • 2019-09-17
    • 2019-03-24
    • 2018-05-12
    • 2020-06-12
    • 1970-01-01
    • 2020-06-03
    相关资源
    最近更新 更多