如何将具有命名操作的 DocumentNode 列表合并到具有 graphql 中各自命名操作的单个 DocumentNode 中?

问题描述 投票:0回答:1

我正在开发必须查询 graphql 来获取数据的应用程序,但是当我使用 graphql 提供的

concat_ast
将 DocumentNode 列表合并到单个 DocumentNode 中时,我收到以下错误
graphql.error.graphql_error.GraphQLError: This anonymous operation must be the only defined operation

我知道发生这种情况的原因,这是我组合查询时发生的情况的示例,concat 函数在每个命名操作周围添加额外的大括号,这是不正确的 graphql 查询语法

组合查询

{
  table1: fetchTable1(
    id: [5, 45]
    perPage: 5
    currentPage: 1
  ) {
    data {
      id
      name
    }
  }
}

{
  table2: fetchTable2(table1_id: [5, 45], perPage: 5, currentPage: 1) {
    data {
      id
      customer
    }
  }
}

单独查询,table2是其命名操作

{
  table2: fetchTable2(table1_id: [5, 45], perPage: 5, currentPage: 1) {
    data {
      id
      customer
    }
  }
}

但是我需要合并结果采用以下格式,以便所有操作都被命名,我也在 apollo graphql UI 中尝试过这个查询,它有效,但我无法在 python 中使用 concat 生成一个,有吗我可以通过任何其他方式组合多个

DocumentNode
而不影响现有的命名操作。

{
  table1: fetchTable1(
    id: [5, 45]
    perPage: 5
    currentPage: 1
  ) {
    data {
      id
      name
    }
  }

  table2: fetchTable2(table1_id: [5, 45], perPage: 5, currentPage: 1) {
    data {
      id
      customer
    }
  }
}

我尝试过使用graphql提供的

concat_ast
函数,我还有一个解决方法,就是不要之前为每个表创建DocumentNodes,并在最后合并所有表
dict
并创建一个DocumentNode,但它会最好让 graphql 将 DocumentNode 合并到一个或任何其他比我更好的解决方案中,因为我可能需要在应用程序的其他部分获取单个表。

python graphql apollo gql
1个回答
0
投票

我们可以使用 graphql-query 包在 python 中组合 GraphQL 查询。

代码

from graphql_query import Argument, Field, Operation, Query

fetchTable1 = Query(
    name="fetchTable1",
    alias="table1",
    arguments=[
        Argument(name="id", value=[5, 45]),
        Argument(name="perPage", value=5),
        Argument(name="currentPage", value=1),
    ],
    fields=[Field(name="data", fields=["id", "name"])]
)

fetchTable2 = Query(
    name="fetchTable2",
    alias="table2",
    arguments=[
        Argument(name="table1_id", value=[5, 45]),
        Argument(name="perPage", value=5),
        Argument(name="currentPage", value=1),
    ],
    fields=[Field(name="data", fields=["id", "customer"])]
)

operation = Operation(
    type="query",
    queries=[fetchTable1, fetchTable2],
)

print(operation.render())

结果是

query {
  table1: fetchTable1(
    id: [5, 45]
    perPage: 5
    currentPage: 1
  ) {
    data {
      id
      name
    }
  }

  table2: fetchTable2(
    table1_id: [5, 45]
    perPage: 5
    currentPage: 1
  ) {
    data {
      id
      customer
    }
  }
}

并创建

DocumentNode
:

query = gql(operation.render())
© www.soinside.com 2019 - 2024. All rights reserved.