GraphQL pagination in Rails
Tags: graphql, pagination, webdev, rails
Published: 2019-06-19 08:13:22

---
title: GraphQL pagination in Rails
published: true
description: 
tags: graphql, pagination, webdev, rails 
cover_image: https://thepracticaldev.s3.amazonaws.com/i/2fg82ly5azxu8iolkaez.png
canonical_url: https://www.2n.pl/blog/graphql-pagination-in-rails
---

##GraphQL cursor pagination in Rails.

So you implemented some graphQL types but it just turns out that returning bazillions of records with each query introduces some performance issues. "It would be nice to have some pagination" you think to yourself. In this post we gonna build graphQL cursor-based pagination functionality. The intent of this post is to show as simple and straightforward as possible how to implement graphQL pagination in graphql-ruby. We'll also cover some nasty edge cases, so they won't ambush you in the wild ;)

###Setup

I assume you are using the following ruby and gem versions:

  ruby 2.5 
  rails 5.2
  graphql-ruby 1.8.7

First, let's create post model:
![](https://thepracticaldev.s3.amazonaws.com/i/szugw0bpfkd0gyvishbt.png)
And seed some sample data to play with:
![](https://thepracticaldev.s3.amazonaws.com/i/rvrypywapbu8xlflnt02.png)
It's time for graphQL post type:
![](https://thepracticaldev.s3.amazonaws.com/i/mkngbr8fqp7v6dktponx.png)
Let's attach it to graphQL schema:
![](https://thepracticaldev.s3.amazonaws.com/i/n4vrz6lsqpv1dy9rcv72.png)
For now, query for this resource looks like this:
![](https://thepracticaldev.s3.amazonaws.com/i/ip2tqc9lu6mu7duk9gwq.png)
and graphQL is politely returning all hundred posts:
![](https://thepracticaldev.s3.amazonaws.com/i/2rx26k885x0g0u2tbouc.png)

But of course it's not quite what we want. So, let's implement basic cursor pagination.

###Pagination

For type with cursor pagination - aka connection, as it has been named by Facebook - we need to define... connection. To do so we are going to add another field to query type:
![](https://thepracticaldev.s3.amazonaws.com/i/uml5gsmnbt3mejdghz7f.png)
As you can see it's pretty straightforward. The interesting part here is invocation of connection_type which will create **connection type** for **Types::PostType**. Actually, we are done! Now the simplest query for this connection type goes like this:
![](https://thepracticaldev.s3.amazonaws.com/i/dlcl3kxxf6ksrj9k3y9d.png)
which returns records in following form:
![](https://thepracticaldev.s3.amazonaws.com/i/2p67xe2eohekeyv3hze2.png)

Query and its result looks more complicated, that's for sure, but where is the actual pagination? For this, graphql-ruby exposes another field in all connection types called **pageInfo**. There is also an additional **cursor** field under **node** which will contain a unique id for given node (it's not identical to post record id!). The final query takes following form:
![](https://thepracticaldev.s3.amazonaws.com/i/dim0c4zdky57wy3aebud.png)

As you probably noticed **postsConnection** above takes additional argument: **first** which is pretty self explanatory: "query for the first 3 edges (records)". Aforementioned **pageInfo** field provides us with, as name suggests, pagination-related info. It's fields are self explanatory I believe. The final result:
![](https://thepracticaldev.s3.amazonaws.com/i/gah37lfv2v82g20868an.png)
to get to the next page we'll provide postsConnection with additional argument:
![](https://thepracticaldev.s3.amazonaws.com/i/jxlq6wbpzc8nxqehowcv.png)
...which translates to: "query for the first 3 records after node with cursor(node id): **NA==**"

###Gotcha 1: **hasPreviousPage** and **hasNextPage**

You might presume that **hasPreviousPage** and **hasNextPage** will provide you with info suggested by its name. GraphQL has a little nasty suprise for you there: **hasNextPage** has valid info only when you paginate forward, for example: **postsConnection(first: 3)**. Analogous **hasPreviousPage** when you go backward: **postsConnection(last: 3)**. It will become more clear when you'll look at the example below:

Let's query for first 5 cursor ids:
![](https://thepracticaldev.s3.amazonaws.com/i/3jeyfuwewamxj1bajvxo.png)
First 5 cursors:
![](https://thepracticaldev.s3.amazonaws.com/i/u3xawpoldaptsvh9i9po.png)
Now let's query for 2 records after second one **Mg==**:
![](https://thepracticaldev.s3.amazonaws.com/i/rzdm9n2k1eshyagjitnx.png)
We get **pageInfo**:
![](https://thepracticaldev.s3.amazonaws.com/i/qknzdqr42z3pdcuywlr8.png)

Despite 2 records still being on the previous page, we still get **"hasPreviousPage": false**. That's right: not **null** or **undefined** but obviously incorrect **false**. And it's not a bug. It's this way by design.

Explanation for this is that at Facebook, where GraphQL has its origins, infinite scroll is a way to go for pagination(news feed for example). And for this purpose, information about previous page when you scroll down is just not needed. It would only introduce unnecessary performance overhead. One simple way to mitigate this in the current state of affairs(not very elegant though...) is to make additional query, just to check if there is a previous page. So for the query above it would look like this:
![](https://thepracticaldev.s3.amazonaws.com/i/h50ch7gjr7z49ri3ijdb.png)
..which provides us with correct **hasPreviousPage** info this time:
![](https://thepracticaldev.s3.amazonaws.com/i/fum4urjaeyfagn97psu4.png)

###Gotcha 2: **pageCount**

So, you would probably like to know how many pages there is actually. To calculate this, you could do the following: **total_records_count / records_per_page_count**. So all you really need is info about total records count. It would be nice to query for it like this:
![](https://thepracticaldev.s3.amazonaws.com/i/6pvkx2kvwdpxj1t0kqdc.png)
Unfortunately, running this query will result in:
![](https://thepracticaldev.s3.amazonaws.com/i/4ae8yk6lt45ttiih9bm5.png)

In fact, there is no way to get this info from default connection. The reason is the same as in the case of previous and next page info: total records count is not really needed for infinite scroll pagination and would only introduce performance overhead. The good news is that it can be quite easily implemented though :)

First, we need to define manually our custom connection:
![](https://thepracticaldev.s3.amazonaws.com/i/whrem6wodvhfe7chzaj5.png)
So, to define our custom connection we define a class which inherits from a base graphql connection class: **GraphQL::Types::Relay::BaseConnection**. We also have to define by hand an edge class **PostsEdgeType** and then specify that we are going to use it in our connection: **edge_type(PostsEdgeType)**. Finally way we can add additional fields, like total_count in our example, just the way you would do this in other type classes, like **Types::PostType**.

Next, we need to specify that we are going to use **Types::PostsConnection** as posts_connection type class:
![](https://thepracticaldev.s3.amazonaws.com/i/1dy74yy51js7w0zkuzob.png)
Now, our query with total count works as expected:
![](https://thepracticaldev.s3.amazonaws.com/i/040fxiifnimh2asmdh31.png)
![](https://thepracticaldev.s3.amazonaws.com/i/taatwme2d908hm9v93ly.png)

The drawback of this approach, is of course, that with **totalCount** we are introducing N+1 to our connection. Also, watch out for class name used for our custom connection. It has to end with **Connection** (as in our case **Types::PostsConnection**) to be treated by graphql-ruby as connection. If you need a different naming convention you can state explicitly that a connection type will be used in field definition:
![](https://thepracticaldev.s3.amazonaws.com/i/5e6da8n3z3jmwh4mp70e.png)

###Conclusion

GraphQL, along with its implementations (like graphql-ruby in our case) is still a very young technology and under rapid development. Thus, there is lack of conventions that would be widely accepted by community, as we are used to in the Rails world. This also applies to graphQL pagination and we should expect changes to its specification and implementation in the future. But until then, this post should prove to be useful on your graphQL path ;)

Full application code can be found [here](https://github.com/KamilMilewski/graphql_examples_for_blog/tree/cursor_pagination).