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
Adding pagination is really simple. All you have to do is add this file app/graphql/queries/books_connection.rb
and of course edit app/graphql/types/query_type.rb
with:
Please note that Types::BookType
looks like:
If you wonder about Types::AuthorType
and 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,
BookEdge
represents the link fromAuthor
toBook
. 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 aBook
.
Pagination usage
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 BooksQuery
execution:
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 Pagination
Testing connection is no different than testing regular query:
Summary
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.
Happy coding!