Apollo Server - 根据孩子有选择地返回数组成员

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

我正在使用 Node.js Apollo Server (4.3.0) 返回相当复杂的 GraphQL。这里大大简化了,我有一个

Connection
Child
对象可以直接查询,还有一个
Connection
Parent
对象可以包含相同的
ChildConnection
.

type Query {
  parentQuery(first: Int, after: String): ParentConnection
  childQuery(first: Int, after: String): ChildConnection
}

type ParentConnection: {
  edges: [ParentEdge!]
  pageInfo: PageInfo
}
type ParentEdge: {
  node: Parent
  cursor: String
}
type Parent: {
  children(first: Int, after: String): ChildConnection
}

type ChildConnection: {
  edges: [ChildEdge!]
  pageInfo: PageInfo
}
type ChildEdge: {
  node: Child
  cursor: String
}
type Child {
  id: ID!
}

调用

parentQuery
时出现问题,要求整棵树。有时,特定
children
Parent
字段没有边,发送给客户端时无用。我想从查询响应中省略这个
ParentEdge
,而不是在客户端剥离它,这看起来既浪费又容易出错。

在 Apollo 服务器中,这通常没问题——直接向下调用您的解析器树,等待结果,为父级返回 null 或干脆不将其添加到连接中。这里的复杂之处在于

ChildConnection
采用通常的
Connection
args,而在 Apollo Server 中,子级的 args 对父级不可用。因此,尝试从
ParentConnection
级别解析树将忽略
ChildConnection
args。尝试从
Parent
级别解析树,最多允许您通过
ParentEdge
字段修改
parent
解析器,从而在
ParentConnection.edges
字段中留下空条目。

将 args 从

children
Parent
字段提升到
parentQuery
将解决问题,但它将设计架构以匹配实现,而不是遵循连接最佳实践。

我心目中的两个干净的解决方案是:

  1. 为父解析器提供访问其子参数的方法,或者
  2. 在解决了整个树之后,有办法在解析器上执行处理。甚至可能在整个查询完成之后。
graphql apollo apollo-server
© www.soinside.com 2019 - 2024. All rights reserved.