自省查询对 buildClientSchema 无效

Introspection Query is invalid for buildClientSchema

我正在尝试使用 npm GraphQL 库将内省查询转换为 GraphQL 模式。

它一直在说:

devAssert.mjs:7 Uncaught Error: Invalid or incomplete introspection result. Ensure that you are passing "data" property of introspection response and no "errors" was returned alongside: { ... } 

问题是我直接从 GraphiQL Shopify 获取它,无法弄清楚如何验证我的自省 return 是否正确。

代码:

var introspection = `
{
  "data": {
    "__schema": {
      "types": [
        {
          "name": "Boolean"
        },
        {
          "name": "String"
        },
        {
          "name": "QueryRoot"
        },
        {
          "name": "Job"
        },
        {
          "name": "ID"
        },
        {
          "name": "Node"
        },
        {
          "name": "Order"
        }
      ]
    }
  },
  "extensions": {
    "cost": {
      "requestedQueryCost": 2,
      "actualQueryCost": 2,
      "throttleStatus": {
        "maximumAvailable": 1000,
        "currentlyAvailable": 980,
        "restoreRate": 50
      }
    }
  }
}`;

      let schema = buildClientSchema(introspection);
      //console.log(schema.printSchema());

我以为内省的结果是字符串?还是没有足够的信息来构建模式?我需要扩展字段数吗?将内省结果交换为模式所需的最低限度是多少?

您应该使用 getIntrospectionQuery 来获取所需的完整内省查询。如果您正在使用的响应是一个字符串,那么在传递给 buildClientSchema 之前应该将其解析为一个对象——该函数接受一个对象,而不是一个字符串。

下面是一个使用 graphql 函数直接查询模式的示例 -- 您需要根据实际执行查询的方式对其进行修改。

const { getIntrospectionQuery, buildClientSchema, graphql } = require('graphql')

const schema = new GraphQLSchema(...)
const source = getIntrospectionQuery()
const { data } = await graphql({ source, schema })
const clientSchema = buildClientSchema(data)

确保您只传递响应的 data 部分。您传入的对象应如下所示:

{
  __schema: {
    // ...more properties
  }
}