Keys
Key
is an identifier used to uniquely represent the data you want to fetch.
const DataLoader = require('frontend/contents/graphql/dataloader/a.start'); async function batchUsers(userIds) { // Fetch users in bulk using the array of user IDs const users = await getUsersByIds(userIds); return userIds.map(id => users.find(user => user.id === id)); } // Create a DataLoader for users const userLoader = new DataLoader(keys => batchUsers(keys)); const resolvers = { Query: { // The `id` is the key user: (parent, { id }) => userLoader.load(id) } };
context
arg to call the Dataloader
to maintain single instance of Dataloader
const { createLoader } = require('./a.start'); // Function to create DataLoader const resolvers = { Query: { users: async (_, args, context) => { // Create a new instance of DataLoader const userLoader = createLoader(); // Fetch some users from a DB const users = await fetchUsers(); // loads to DataLoader per request const usersWithPosts = await Promise.all(users.map(user => { return { ...user, posts: userLoader.load(user.id) // Load related data using DataLoader }; })); return usersWithPosts; }, }, User: { posts: (parent, args, context) => { // previously defined loader is called here // Use DataLoader for batching and caching return context.userLoader.load(parent.id); }, } };