如何修改GraphQL的info对象SelectionSet以正确获取目标FieldNode?
问题解决方法
你当前拿到的info.field_nodes[0]是顶层查询字段(即allLibrary)对应的AST节点,它的选择集只包含allLibrary下直接请求的results、__typename字段,目标字段name、book是嵌套在results字段的选择集内的,按以下步骤调整即可获取:
- 从顶层字段的选择集中筛选出
results对应的FieldNode - 访问
results节点的selection_set.selections属性,即可得到目标字段的FieldNode列表
代码示例
from graphql import FieldNode # 取顶层allLibrary字段的所有子选择 top_selections = info.field_nodes[0].selection_set.selections # 筛选results字段的FieldNode results_node = next( sel for sel in top_selections if isinstance(sel, FieldNode) and sel.name.value == "results" ) # 非空判断避免查询未指定results子字段时报错 if results_node.selection_set: target_selections = results_node.selection_set.selections # 此处target_selections就包含你需要的name、book等FieldNode
如果存在多层嵌套的查询场景,可以通过递归遍历每个FieldNode的selection_set的方式,提取任意层级的请求字段。
内容的提问来源于stack exchange,提问作者Lukasz Dynowski
相关产品推荐
相关产品推荐

