Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass total count to the client in pageInfo

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

like image 340
Christine Avatar asked Dec 10 '15 02:12

Christine


2 Answers

pageInfo is designed to represent information about the specific page, whereas the total number of items is really a property of the connection itself. We recommend adding a count field to the connection. You might query it with:

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

Relay supports arbitrary fields on a connection, so you're free to name this count, totalCount, etc.

like image 71
Joe Savona Avatar answered Oct 11 '22 14:10

Joe Savona


Thank you @Joe Savona

He is absolutely right. Since it took me a moment to figure out how to actually add the property to the connection on the server site I thought I share that here as well:

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.`
    }
  })
});

Hope that helps others.

Cheers

like image 30
Christine Avatar answered Oct 11 '22 13:10

Christine