为什么 Relay+GraphQL 连接中没有 'position' 参数?

Why is there no 'position' argument in Relay+GraphQL connections?

GraphQL 和 Relay 具有强大的分页算法,可以为最终用户轻松分页,即使在无限制和顺序无关的结果中也允许分页。

但是,我有一个用例,我不太确定如何在 GraphQL 和中继中进行操作,很容易我确定我只是错过了一些东西。

例如,如果我的列表已排序(通过 orderBy 参数),我如何获取第 5 项(并且只有第 5 项)?

如果您在后端有一个有序列表,并且您想要获取特定位置的元素,只需将位置值指定为查询字段的参数即可。查询字段的代码如下所示:

employee: {
  type: EmployeeType,
  args: {
    position: {
      type: new GraphQLNonNull(GraphQLInt)
    },
    ...args,
  },
  resolve: async (context, {position, ...args}) => {
    // Get the ordered list of employees, probably from cache.
    // Pick the employee with the requested position in the list.
    // Return the employee.
  },
},

这没有很好的记录,但这里是如何做的。

query {
  allPeople(first: 5, last: 1) {
    edges {
      node {
        name
      }
    }
  }
}

首先你 select first: 5 获得列表中的前 5 个人。然后,执行 last:1 子集 中获取最后一个人。换句话说——得到第五个人。

如果你这样做 (first: 5, last: 2) 你会得到列表中的第 4 和第 5 个人。

Demo (如果它 returns 是一个错误 - 在查询中手动重新输入单词 query 它将起作用)。然后,在没有 firstlast 的情况下再次尝试查看整个列表,您会看到 Leia 排在第 5 位。