How do you implement a DataLoader with batching and caching?
Answer
DataLoader batches and caches within a single request. Implementation: import DataLoader from 'dataloader';. Define a batch function: const batchUsers = async (ids) => { const users = await User.findAll({ where: { id: ids } }); return ids.map(id => users.find(u => u.id === id) || new Error(`User ${id} not found`)); };. Note: the batch function must return an array in the same order as the input IDs array — this is critical. Create per-request: const userLoader = new DataLoader(batchUsers);. Use: const user = await userLoader.load(userId);. Multiple loads in one tick are batched: const [u1, u2] = await Promise.all([userLoader.load(1), userLoader.load(2)]) → one DB query. Cache: userLoader.load(1) called twice returns the same Promise. Disable cache for mutations: userLoader.clear(userId) after update. Create loaders in the context factory so each request gets fresh instances.
More GraphQL Questions
View all →- Intermediate How do you implement pagination in GraphQL?
- Intermediate What is the Relay specification in GraphQL?
- Intermediate How do you implement authorization in GraphQL resolvers?
- Intermediate What is graphql-shield and how does it work?
- Intermediate How do you implement real-time subscriptions with GraphQL?