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.
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
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