Problem:
Our client doesn’t want to request a long list of items at once. We want to get our posts query to return items in batches.
Solution:
Cursor-based pagination.
This will allow us to return pages of items, but without the drawbacks of offset-based pagination (where pages could possible shift between queries as items are added or deleted).
Cursor-based pagination requires 2 key arguments to the resolver:
cursor: a marker that identifies the “latest” item returned.limit: how many items to return in the page
Implementation:
2 key steps:
1. Schema: Take cursor and limit arguments into our posts query
2. Resolver: Use the new args to construct our database query
We can now test this query on our seed data in GraphQL Playground.
query {
posts(limit: 2) {
id
text
createdAt
}
}Then we can then use the createdAt value of the last post in the page as the cursor for our next query.
query {
posts(limit: 2, cursor: "2019-06-17T04:30:12.099Z") {
id
text
createdAt
}
}Possible Improvements:
Use opaque cursors: base64 encode cursor values so the client isn’t concerned with the value itself.
Use a GraphQL Connection to provide more info to the client
hasNextPagereturn
edgesandnodesAllows us to put metadata on the edges if we want