如何在 Graphql 中继中处理连接内的列表

How to Handle List inside Connection in Graphql Relay

我有这样的架构:

type SectionItem = {
  a: String
}

type SectionRowConnection {
  pageInfo: PageInfo!
  edges: [SectionRowEdge]
}

type SectionRowEdge {
  node: [SectionItem]
  cursor: String!
}

我想在每个连接节点中获取一个列表,当我运行下面手动查询时,一切正常:

query {
  sectionRows(type:someType){
    edges{
      node{
        a
      }
    }
  }
}

现在我在客户端中使用 Relay,但我在尝试使用 relay 构建查询时遇到此错误:

ERROR: Encountered 1 error(s): - @connection used on invalid field sectionRows. Expected the field type SectionRowConnection to have an edges { node } field that returns an object, interface, or union.

正如错误提示的那样,我不能在中继连接中使用 List,但我想要一个这样的模式,关于如何将中继与此模式一起使用的任何想法或推荐解决此问题的解决方法?

来自中继 spec:

An “Edge Type” must contain a field called node. This field must return either a Scalar, Enum, Object, Interface, Union, or a Non‐Null wrapper around one of those types. Notably, this field cannot return a list.

也就是说,SectionRowConnection不符合Relay对连接类型的要求,因为它的节点字段是一个List。除了修改架构以使 node 的类型为 SectionItem! 而不是 [SectionItem] 之外,没有解决此问题的方法。如果要使用 Relay,您的架构必须符合 Relay 规范。

连接本身代表单个节点的集合(或者 "resources" 如果我们借用 REST 术语),每条边将根节点连接到集合中的单个节点。

例如,我们可以想象一个具有 friends 字段的单个用户节点,该字段 return 是一个 UserConnection。连接中的每条边代表原始用户节点和其中一个朋友用户之间的关联。每条边都有一个用户节点。

这个用户节点的集合自然可以根据需要进行排序和过滤。但是,如果我们想根据某些标准(类似于 SQL 中的 GROUP BY)将它们 group 在一起,我们将创建一个单独的 UserGroup 类型和一个 UserGroupConnection。 UserGroupConnection 中的每个 UserGroup 节点本身都会有一些字段,即 UserConnection。即使在这种情况下,每个连接的边缘仍然只有一个节点

如果您只是尝试进行简单的过滤或 "grouping" 您的节点(如上所示),那么仅从您的架构中还不清楚。无论哪种方式,从概念上讲,没有理由为它的 node 字段设置边 return 列表。

我最终做的是将结果列表包装在一个对象中,即每个节点都是 SectionRow 类型,即具有 items 字段的 graphQlObjectType,列表在项目列表中。这是生成的架构:

type SectionItem = {
  a: String
}

type SectionRow = {
  items: [SectionItem]
}

type SectionRowConnection {
  pageInfo: PageInfo!
  edges: [SectionRowEdge]
}

type SectionRowEdge {
  node: SectionRow
  cursor: String!
}