首页 > 解决方案 > 如何从 Apollo Server 端点获得完整的 GraphQL 架构?

问题描述

我正在使用 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 内部,只需通过端点访问模式)

标签: graphqlapollo-serverkeystonejsgraphql-schema

解决方案


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

这是一个使用 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.


推荐阅读