In the last episode, we divided queries into separate files. You can find all the necessary information in this article. Today we will add a pagination endpoint and explain how to use it.
Adding GraphQL pagination might be tricky because there are quite a lot of different implementations. In this tutorial, we are going to use the one that is suggested by graphql-ruby.org. We will be preparing a separate query file so make sure that you are familiar with this concept first.
Adding pagination is really simple. All you have to do is add this file
and of course edit
Please note that
Types::BookType looks like:
If you wonder about
Enums::Genre, please visit the first article from this series.
As you can see implementation is trivial but we have to dive into some theory and naming convention in order to understand how to use this pagination correctly.
Connections, edges and nodes
- Connection - it exposes pagination-related metadata and access to the nodes and edges. In our example we have created
BookConnection. Connections are objects that represent a one-to-many relation.
- Edge - represents the relationship between the parent and child. In our example,
BookEdgerepresents the link from
Book. Edges help when the relationship between two objects has special data associated with them. You might need a custom edge to model the relationship if you use a join table.
- Node - actual list item. For our
BookConnection, each node is a
We have pagination in place and we know what each of the object names stands for. Let’s try to use it! I think it is a good idea to compare pagination to regular
Simple connection usage looks like this:
In order to access pagination features we have to use PageInfo. We also can receive cursor info for each node at edge level:
We can use cursor to start a “new page”:
Testing connection is no different than testing regular query:
I hope that you found this tutorial useful and comprehensive. Adding pagination for your query is relatively simple but if you are looking for more information please take a look at graphql-ruby.org.