• Design
  • Shotty
  • Blog
  • Reading
  • Photos
Menu

Jacob Ruiz

Product Designer
  • Design
  • Shotty
  • Blog
  • Reading
  • Photos
graphql-notes@2x.png

GraphQL Pagination: Opaque Cursors

June 19, 2019

Why use an opaque cursor?

We want to let the cursor be a cursor, and nothing more. Rather than using a createdAt date as the cursor value, we can use a base64 encoded string (generated from the createdAt date). This serves as a reminder to the client to not rely on the cursor value to be of any particular type or have any particular meaning other than being a marker to identify the last item in the returned page. The client then passes this string as the cursor argument in the next page query to tell the API, “here’s where I left off last time, get me the next X number of items.”

Implementation

We need to to a few key things:

  1. Create helper functions that encode and decode a string to and from base64.

    • toCursorHash

      • This is how we serialize any value with meaning into a “meaningless” cursor value

    • fromCursorHash

      • The corresponding function to decode the cursor hash and give it meaning again, so our resolver can use it in the database query.

  2. Encode the createdAt date of the last retrieved node before putting it into the pageInfo object as the endCursor.

  3. Decode the opaque cursor value (back into a meaningful createdAt date) before using it in our resolver’s query to the database.

  4. Update our schema so that the endCursor field on the PageInfo type returns a String instead of a Date

Here’s what each of these looks like:

Helper functions

Resolver

Schema

Does it work?

Running the posts query in GraphQL Playground now returns an opaque string as the endCursor in the pageInfo object. We can use that string as the cursor argument in our next query.

Screen Shot 2019-06-20 at 10.22.46 AM.png
Screen Shot 2019-06-20 at 10.24.26 AM.png

Sources:

The Road To GraphQL

GraphQL Docs: Pagination

Apollo Docs: Pagination

Apollo Blog: Explaining GraphQL Connections

← GraphQL Pagination: Putting It All TogetherGraphQL Pagination: hasNextPage →
shotty-skinny2x.jpg

Shotty - Faster Access To Your Screenshots on Mac

Shotty is an award-winning Mac app I created to give you instant access to all your recent screenshots, right from the menu bar. You can even add annotations on-the-fly. Stop wasting time digging through Finder for your screenshots. I promise it’ll change your workflow forever (just read the App Store reviews!).



Most popular

information-architecture

Information Architecture: The Most Important Part of Design You're Probably Overlooking

Follow @JacobRuizDesign