How to pass total count to the client in pageInfo

时间:2015-12-10 02:06:45

标签: javascript reactjs relayjs graphql-js

I use first after and last before to do pagination. hasNextPage and hasPreviousPage are very useful.

But what I need is also the total count so that I can calculate and show things like page 5 of 343 pages on the client.

Unfortunately that is not part of pageInfo even though I have the information on the server site.

Can you please include a total field in the pageInfo and extend connectionFromArray to take in the total arrayLength like connectionFromArraySlice already does?

Thanks

3 个答案:

答案 0 :(得分:11)

pageInfo旨在表示有关特定页面的信息,而项目总数实际上是连接本身的属性。我们建议在连接中添加count字段。您可以使用以下方式查询:

fragment on TodoList {
  tasks(first: 10) {
    count # <-- total number of tasks
    edges { ... }
    pageInfo { ... }
}

Relay支持连接上的任意字段,因此您可以自由命名此counttotalCount等。

答案 1 :(得分:8)

谢谢@Joe Savona

他是绝对正确的。由于我花了一些时间来弄清楚如何将属性实际添加到服务器站点上的连接,我想我也在这里分享:

var {connectionType: postsConnection} = connectionDefinitions({
  name: 'post',
  nodeType: qlPost,
  connectionFields: () => ({
    totalCount: {
      type: GraphQLInt,
      resolve: (connection) => connection.totalCount,
      description: `A count of the total number of objects in this connection, ignoring pagination.
This allows a client to fetch the first five objects by passing "5" as the
argument to "first", then fetch the total count so it could display "5 of 83",
for example.`
    }
  })
});

希望能帮助他人。

干杯

答案 2 :(得分:0)

一段时间以来,我在连接上使用了自定义totalCount字段,但是它引入了我一开始没有看到的复杂性(当突变后更新连接时,如果需要,您必须使用相同的参数来查询它)自动更新)。

因此,我回到了每个连接旁边的一个count字段。在您的例子中,这意味着:

fragment on TodoList {
  taskCount
  tasks {
    edges { ... }
  }
}

然后我创建了一个小助手来为我创建它:https://github.com/rea-app/relay-connection-count