Background

I have a GraphQL server on which I’ve deliberately limited the amount of data that can be returned in a single query to avoid daft requests. That means that you need to do paging to get a set of results of more than that limit. There are various ways of paging in GraphQL, but this one uses  a simple system of limits and offsets to get chunks of results. Something like this
That leaves the problem of how exactly to do queries like this when the calls themselves are asynchronous. If they were synchronous, then a simple recursive approach would be easy enough to implement, but asynchronous calls are a little more tricky. Using Promises improves things a little, but using ES6 “await” makes it no more complex than a synchronous solution. Let’s take a look.

Fetcher

Start with a simple fetcher (I’m using axios) that makes a request given a query an some optional variables.

Pager

The pager is called to bunch up pages of graphql results into a single response. The inline comments describe what’s going on, but in summary
  • Pages are recursively fetched until either there are no more or the max requested is reached.
  • After each page, the offset and limit variables are tweaked to get the next page.
  • The use of await means it reads almost like a synchronous recursion

Using it

Get all the people named smith in a single result
For more like this see Google Apps Scripts Snippets

For help and more information join our community,  follow the blog,  follow me on Twitter