zach.codes

Share this post

User's avatar
zach.codes
GraphQL Query Batching Solutions
Copy link
Facebook
Email
Notes
More

GraphQL Query Batching Solutions

Zach Silveira
Jul 28, 2017
∙ Paid

Share this post

User's avatar
zach.codes
GraphQL Query Batching Solutions
Copy link
Facebook
Email
Notes
More
Share
GraphQL Query Batching Solutions

I've been using Apollo for a few months now and the one problem not well documented is query batching. Most of the getting started guides don't even mention it. This is a shame considering almost all apps would need to fetch data from some sort of database. These principles can be taken to other GraphQL implementations as well, but the code shown is specific to node in this tutorial.

Two Query Minimum: Dataloader

The first solution is Facebook's Dataloader. I'm a little surprised at how complicated the documentation makes this library seem, when it's actually simple to use. I define a dataloader in the same place as my model for each database table:

import DataLoader from 'dataloader';

export const categoryLoader = new DataLoader(async ids => {
  let categories = await Category
    .query()
    .whereIn('id', ids);

  return ids
    .map(
      id => categories.find(
        category => category.id === id
      )
    );
});

The second part (mapping through the result and reordering) is…

Keep reading with a 7-day free trial

Subscribe to zach.codes to keep reading this post and get 7 days of free access to the full post archives.

Already a paid subscriber? Sign in
© 2025 Zach Silveira
Privacy ∙ Terms ∙ Collection notice
Start writingGet the app
Substack is the home for great culture

Share

Copy link
Facebook
Email
Notes
More