Skip to content

A GraphQL batching model which groups execution by GraphQL fields.

License

Notifications You must be signed in to change notification settings

calebmer/graphql-resolve-batch

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

35 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

GraphQL Batch Resolver

A method for batching the resoluition of GraphQL fields as an alternative to dataloader that works with both GraphQL.js and graphql-tools.

import { GraphQLObjectType, GraphQLString } from 'graphql';
import { createBatchResolver } from 'graphql-resolve-batch';

const UserType = new GraphQLObjectType({
  // ...
});

const QueryType = new GraphQLObjectType({
  name: 'Query',
  fields: {
    user: {
      type: UserType,
      resolve: createBatchResolver(async (sources, args, context) => {
        const { db } = context;
        const users = await db.loadUsersByIds(sources.map(({ id }) => id));
        return users;
      }),
    },
  },
});

For a complete examples with usage for both GraphQL.js and graphql-tools, be sure to check out the ./examples directory.

Installation

graphql-resolve-batch has a peer dependency on graphql, so make sure you have installed that package as well.

npm install --save graphql graphql-resolve-batch

Why?

GraphQL is a powerful data querying language for both frontend and backend developers. However, because of how GraphQL queries are executed, it can be difficult to define an efficient GraphQL schema. Take for example the following query:

{
  users(limit: 5) {
    name
    friends(limit: 5) {
      name
    }
  }
}

This demonstrates the power of GraphQL to select arbitrarily nested data. Yet it is a difficult pattern to optimize from the schema developer’s perspective. If we naïvely translate this GraphQL query into say, SQL, we get the following pseudo queries:

Select the first 5 users.
Select th