Jacob Ruiz

View Original

GraphQL Pagination

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

See this content in the original post

2. Resolver: Use the new args to construct our database query

See this content in the original post

We can now test this query on our seed data in GraphQL Playground.

See this content in the original post

Then we can then use the createdAt value of the last post in the page as the cursor for our next query.

See this content in the original post

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

    • hasNextPage

    • return edges and nodes

      • Allows us to put metadata on the edges if we want