Implementing DataLoader in Node.js
A DataLoader should normally be created for each GraphQL request rather than globally shared between users. This prevents data from one request being accidentally reused by another request.
Author DataLoader
import DataLoader from "dataloader";
const createAuthorLoader = () =>
new DataLoader(async (authorIds) => {
const authors = await User.find({
_id: { $in: authorIds }
});
const byId = new Map(
authors.map(author => [author.id, author])
);
return authorIds.map(id => byId.get(id) || null);
});
const context = ({ req }) => ({
user: req.user,
loaders: {
author: createAuthorLoader()
}
});The batch function receives all requested author IDs, performs one database operation, indexes the results by ID, and then returns values in the same order as the requested keys.