Today I Learned

hashrocket A Hashrocket project

Cursor Pagination with graphql

When a graphql object has a plural type, each object of the collection from that plural type will have a cursor associated with it. This cursor is generally a base64 encoded unique identifier referencing the search, the object and the place of that object amongst all objects in the collection.

Ask for the cursor as a property when iterating over a collection.

  query {
    User(login: 'jbranchaud') {
      repositories(first: 100) {
        edges {
          node {
            cursor
            name
          }
        }
      }
    }
  }

The above query will return a cursor for each repo.

Get the last cursor of that collection with pageInfo.endCursor:

  query {
    User(login: 'jbranchaud') {
      repositories(first: 100) {
        pageInfo {
          endCursor
          hasNextPage
        }
        edges {
          node {
            name
          }
        }
      }
    }
  }

The endCursor will look like:

Y3Vyc29yOnYyOpHOBK0NoA==

Use this cursor to obtain the next 100 repos with the after property.

  query {
    User(login: 'jbranchaud') {
      repositories(first: 100, after: "Y3Vyc29yOnYyOpHOBK0NoA==") {
        pageInfo {
          endCursor
          hasNextPage
        }
        edges {
          node {
            name
          }
        }
      }
    }
  }
See More #workflow TILs