GiraphQL
Search…
Dataloader
This plugin makes it easy to add fields and types that are loaded through a dataloader.

Usage

Install

To use the dataloader plugin you will need to install both the dataloader package and the giraphql dataloader plugin:
1
yarn add dataloader @giraphql/plugin-dataloader
Copied!

Setup

1
import DataloaderPlugin from '@giraphql/plugin-dataloader';
2
3
const builder = new SchemaBuilder({
4
plugins: [DataloaderPlugin],
5
});
Copied!

loadable objects

To create an object type that can be loaded with a dataloader use the new builder.loadableObject method:
1
const User = builder.loadableObject('User', {
2
// load will be called with ids of users that need to be loaded
3
// Note that the types for keys (and context if present) are required
4
load: (ids: string[], context: ContextType) => context.loadUsersById(ids),
5
fields: (t) => ({
6
id: t.exposeID('id', {}),
7
username: t.string({
8
// the shape of parent will be inferred from `loadUsersById()` above
9
resolve: (parent) => parent.username,
10
}),
11
}),
12
});
Copied!
It is VERY IMPORTANT to return values from load in an order that exactly matches the order of the requested IDs. The order is used to map results to their IDs, and if the results are returned in a different order, your GraphQL requests will end up with the wrong data. Correctly sorting results returned from a database or other data source can be tricky, so there this plugin has a sort option (described below) to simplify the sorting process. For more details on how the load function works, see the dataloader docs.
When defining fields that return Users, you will now be able to return either a string (based in ids param of load), or a User object (type based on the return type of loadUsersById).
1
builder.queryType({
2
fields: (t) => ({
3
user: t.field({
4
type: User,
5
args: {
6
id: t.arg.string({ required: true }),
7
},
8
// Here we can just return the ID directly rather than loading the user ourselves
9
resolve: (root, args) => args.id,
10
}),
11
currentUser: t.field({
12
type: User,
13
// If we already have the user, we use it, and the dataloader will not be called
14
resolve: (root, args, context) => context.currentUser,
15
}),
16
users: t.field({
17
type: [User],
18
args: {
19
ids: t.arg.stringList({ required: true }),
20
},
21
// Mixing ids and user objects also works
22
resolve: (_root, args, context) => [...args.ids, context.CurrentUser],
23
}),
24
}),
25
});
Copied!
GiraphQL will detect when a resolver returns string, number, or bigint (typescript will constrain the allowed types to whatever is expected by the load function). If a resolver returns an object instead, GiraphQL knows it can skip the dataloader for that object.

loadable fields

In some cases you may need more granular dataloaders. To handle these cases there is a new t.loadable method for defining fields with their own dataloaders.
1
// Normal object that the fields below will load
2
interface PostShape {
3
id: string;
4
title: string;
5
content: string;
6
}
7
8
const Post = builder.objectRef<PostShape>('Post').implement({
9
fields: (t) => ({
10
id: t.exposeID('id', {}),
11
title: t.exposeString('title', {}),
12
content: t.exposeString('title', {}),
13
}),
14
});
15
16
// Loading a single Post
17
builder.objectField(User, 'latestPost', (t) =>
18
t.loadable({
19
type: Post,
20
// will be called with ids of latest posts for all users in query
21
load: (ids: number[], context) => context.loadPosts(ids),
22
resolve: (user, args) => user.lastPostID,
23
}),
24
);
25
// Loading multiple Posts
26
builder.objectField(User, 'posts', (t) =>
27
t.loadable({
28
type: [Post],
29
// will be called with ids of posts loaded for all users in query
30
load: (ids: number[], context) => context.loadPosts(ids),
31
resolve: (user, args) => user.postIDs,
32
}),
33
);
Copied!

dataloader options

You can provide additional options for your dataloaders using loaderOptions.
1
const User = builder.loadableObject('User', {
2
loaderOptions: { maxBatchSize: 20 },
3
load: (ids: string[], context: ContextType) => context.loadUsersById(ids),
4
fields: (t) => ({ id: t.exposeID('id', {}) }),
5
});
6
7
builder.objectField(User, 'posts', (t) =>
8
t.loadable({
9
type: [Post],
10
loaderOptions: { maxBatchSize: 20 },
11
load: (ids: number[], context) => context.loadPosts(ids),
12
resolve: (user, args) => user.postIDs,
13
}),
14
);
Copied!
See dataloader docs for all available options.

Manually using dataloader

Dataloaders for "loadable" objects can be accessed via their ref by passing in the context object for the current request. dataloaders are not shared across requests, so we need the context to get the correct dataloader for the current request:
1
// create loadable object
2
const User = builder.loadableObject('User', {
3
load: (ids: string[], context: ContextType) => context.loadUsersById(ids),
4
fields: (t) => ({
5
id: t.exposeID('id', {}),
6
}),
7
});
8
9
builder.queryField('user', (t) =>
10
t.field({
11
type: User,
12
resolve: (parent, args, context) => {
13
// get data loader for User type
14
const loader = User.getDataloader(context);
15
16
// manually load a user
17
return loader.load('123');
18
},
19
}),
20
);
Copied!

Errors

Calling dataloader.loadMany will resolve to a value like (Type | Error)[]. Your load function may also return results in that format if your loader can have parital failures. GraphQL does not have special handling for Error objects. Instead GiraphQL will map these results to something like (Type | Promise<Type>)[] where Errors are replaced with promises that will be rejected. This allows the normal graphql resolver flow to correctly handle these errors.
If you are using the loadMany method from a dataloader manually, you can apply the same mapping using the rejectErrors helper:
1
import { rejectErrors } from '@giraphql/plugin-dataloader';
2
3
builder.queryField('user', (t) =>
4
t.field({
5
type: [User],
6
resolve: (parent, args, context) => {
7
const loader = User.getDataloader(context);
8
9
return rejectErrors(loader.loadMany(['123', '456']));
10
},
11
}),
12
);
Copied!

(Optional) Adding loaders to context

If you want to make dataloaders accessible via the context object directly, there is some additional setup required. Below are a few options for different ways you can load data from the context object. You can determine which of these options works best for you or add you own helpers.
First you'll need to update the types for your context type:
1
import { LoadableRef } from '@giraphql/plugin-dataloader';
2
3
export interface ContextType {
4
userLoader: DataLoader<string, { id: number }>; // expose a specific loader
5
getLoader: <K, V>(ref: LoadableRef<K, V, ContextType>) => DataLoader<K, V>; // helper to get a loader from a ref
6
load: <K, V>(ref: LoadableRef<K, V, ContextType>, id: K) => Promise<V>; // helper for loading a single resource
7
loadMany: <K, V>(ref: LoadableRef<K, V, ContextType>, ids: K[]) => Promise<(Error | V)[]>; // helper for loading many
8
// other context fields
9
}
Copied!
next you'll need to update your context factory function. The exact format of this depends on what graphql server implementation you are using.
1
import { initContextCache } from '@giraphql/core';
2
import { LoadableRef, rejectErrors } from '@giraphql/plugin-dataloader';
3
4
export const createContext = (req, res): ContextType => ({
5
// Adding this will prevent any issues if you server implementation
6
// copies or extends the context object before passing it to your resolvers
7
...initContextCache(),
8
9
// using getters allows us to access the context object using `this`
10
get userLoader() {
11
return User.getDataloader(this);
12
},
13
get getLoader() {
14
return <K, V>(ref: LoadableRef<K, V, ContextType>) => ref.getDataloader(this);
15
},
16
get load() {
17
return <K, V>(ref: LoadableRef<K, V, ContextType>, id: K) => ref.getDataloader(this).load(id);
18
},
19
get loadMany() {
20
return <K, V>(ref: LoadableRef<K, V, ContextType>, ids: K[]) =>
21
rejectErrors(ref.getDataloader(this).loadMany(ids));
22
},
23
});
Copied!
Now you can use these helpers from your context object:
1
builder.queryFields((t) => ({
2
fromContext1: t.field({
3
type: User,
4
resolve: (root, args, { userLoader }) => userLoader.load('123'),
5
}),
6
fromContext2: t.field({
7
type: User,
8
resolve: (root, args, { getLoader }) => getLoader(User).load('456'),
9
}),
10
fromContext3: t.field({
11
type: User,
12
resolve: (root, args, { load }) => load(User, '789'),
13
}),
14
fromContext4: t.field({
15
type: [User],
16
resolve: (root, args, { loadMany }) => loadMany(User, ['123', '456']),
17
}),
18
}));
Copied!

Using with the Relay plugin

If you are using the Relay plugin, there is an additional method loadableNode that gets added to the builder. You can use this method to create node objects that work like other loadeble objects.
1
const UserNode = builder.loadableNode('UserNode', {
2
id: {
3
resolve: (user) => user.id,
4
},
5
// For loadable objects we always need to include an isTypeOf check
6
isTypeOf: (obj) => obj instanceof User,
7
load: (ids: string[], context: ContextType) => context.loadUsersById(ids),
8
fields: (t) => ({}),
9
});
Copied!

Caching resources loaded manually in a resolver

When manually loading a resource in a resolver it is not automatically added to the dataloader cache. If you want any resolved value to be stored in the cache in case it is used somewhere else in the query you can use the cacheResolved option.
The cacheResolved option takes a function that converts the loaded object into it's cache Key:
1
const User = builder.loadableObject('User', {
2
load: (ids: string[], context: ContextType) => context.loadUsersById(ids),
3
cacheResolved: user => user.id,
4
fields: (t) => ({
5
id: t.exposeID('id', {}),
6
...
7
}),
8
});
Copied!
Whenever a resolver returns a User or list or Users, those objects will automatically be added the dataloaders cache, so they can be re-used in other parts of the query.

Sorting results from your load function

As mentioned above, the load function must return results in the same order as the provided array of IDs. Doing this correctly can be a little complicated, so this plugin includes an alternative. For any type or field that creates a dataloader, you can also provide a sort option which will correctly map your results into the correct order based on their ids. To do this, you will need to provide a function that accepts a result object, and returns its id.
1
const User = builder.loadableObject('User', {
2
load: (ids: string[], context: ContextType) => context.loadUsersById(ids),
3
sort: user => user.id,
4
fields: (t) => ({
5
id: t.exposeID('id', {}),
6
...
7
}),
8
});
Copied!
This will also work with loadable nodes, interfaces, unions, or fields.
When sorting, if the list of results contains an Error the error is thrown because it can not be mapped to the correct location. This sort option should NOT be used for cases where the result list is expected to contain errors.

Shared toKey method.

Defining multiple functions to extract the key from a loaded object can become redundant. In cases when you are using both cacheResolved and sort you can use a toKey function instead:
1
const User = builder.loadableObject('User', {
2
load: (ids: string[], context: ContextType) => context.loadUsersById(ids),
3
toKey: user => user.id,
4
cacheResolved: true,
5
sort: true,
6
fields: (t) => ({
7
id: t.exposeID('id', {}),
8
...
9
}),
10
});
Copied!
Last modified 1mo ago