【问题标题】:How can one get a complete GraphQL schema from an Apollo Server endpoint?如何从 Apollo Server 端点获得完整的 GraphQL 架构?
【发布时间】:2020-06-12 13:33:27
【问题描述】:

我正在使用 Apollo Server 在 GraphQL 和 REST 服务之间编写一个 GraphQL 接口。此接口将为 Apollo 客户端前端提供单个 GraphQL 端点。

目前的单一服务是 KeystoneJS 应用程序,它通过(据我所知)Apollo Server 提供 GraphQL 端点。为了暂时保持简单,我从 KeystoneJS 服务器 GraphQL Playground 下载 GraphQL 架构,并将其用作我界面的 GraphQL 架构(在删除 Keystone 生成且 Apollo Server 不理解的定义之后)。

我想自动化这个过程——也就是说,以某种方式“获取”KeystoneJS/Apollo Server 生成的 GraphQL 模式,就像我要从 GraphQL Playground 下载它一样。有没有办法从端点做到这一点? (我不想接触 KeystoneJS 的内部结构,只需通过端点访问架构)

【问题讨论】:

  • 如果您当前正在使用 GraphQL Playground 运行自省查询,您是否有任何理由不能使用您选择的 HTTP 库通过相同的查询向 KeystoneJS 端点发出请求?
  • @DanielRearden -- 我曾想过。我是 GraphQL 的新手,所以以前没有使用过自省。正如我从 graphql.org/learn/introspection 看到的那样,可以获取 JSON,它为您提供有关模式特定方面的信息。我想我可以用它来重建完整模式的 SDL,但我正在使用一个大型模式——目前有 820 行,而且它会增长——有很多嵌套类型。有没有办法通过自省简单地请求整个模式并快速/轻松地将其转换为 SDL?使用自省是否足够容易?
  • 我的错——我忘了​​ Playground 有一个模式的“下载”按钮,所以当你说你是通过 Playground 下载模式时我误解了你。我假设你已经在使用自省来这样做了。

标签: graphql apollo-server keystonejs graphql-schema


【解决方案1】:

您可以对任何 GraphQL 服务运行自省查询(假设它们没有禁用自省 - 某些服务在生产中会这样做)。此查询的结果可以传递给buildClientSchema,以根据自省结果重建模式(自然而然,没有任何字段解析逻辑)。然后,您可以通过调用printSchema 将返回的 GraphQLSchema 对象转换为 SDL。

这是一个使用 axios 的示例,但您可以使用任何您喜欢的 http 库来发出请求:

const { buildClientSchema, getIntrospectionQuery, printSchema } = require('graphql')
const res = await axios.post(ENDPOINT_URL, { query: getIntrospectionQuery() })
const schema = buildClientSchema(res.data.data)
const sdl = printSchema(schema)
console.log(sdl)

注意:第一个“数据”是 axios API 调用来自服务器的实际 JSON 响应,而第二个“数据”是实际的“数据”属性,这是我们要传递给 buildClientSchema 的内容。

【讨论】:

  • FWIW,我想如果您有权访问 Keystone 实例,您也可以使用 executeQuery,而不是使用 axios 进行请求。
  • 这将在一个单独的应用程序中,所以除非我通过 Keystone API 公开它,否则我不会......
猜你喜欢
  • 2019-07-26
  • 1970-01-01
  • 2017-09-05
  • 2020-05-11
  • 2015-04-30
  • 2019-05-02
  • 2020-09-03
  • 1970-01-01
  • 2021-11-14
相关资源
最近更新 更多