graphql - 如何从 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 内部,只需通过端点访问模式)
解决方案
您可以针对任何 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
.
推荐阅读
- amazon-sqs - 使用 SQS 重新总线 - 2 个消费者处理失败消息的次数多于配置的重试次数
- r - 自毁功能
- python - 用cupy(python)计算矩阵的行列式
- javascript - 状态的后 setState 评估
- android-studio - Google Maps Flutter 插件方法未按预期工作
- android - 使用来自 Activity 的导航传递给片段
- excel - 在表格中添加缺失的行 (Excel)
- javascript - 未捕获的类型错误:在进行随机图像选举时无法将属性“src”设置为 null
- python - Flask:如何从服务器中删除文件
- azure - 如何将参数传递给应用服务的源代码管理?