Performance: DataLoader integration
This affects the speed of resolving multiple related data requests by batching and caching them, improving server response time and reducing redundant database calls.
const loader = new DataLoader(async userIds => { const posts = await this.postsService.findByUserIds(userIds); return userIds.map(id => posts.filter(post => post.userId === id)); }); async getUsers() { return Promise.all(users.map(async user => { user.posts = await loader.load(user.id); return user; })); }
async getUsers() { return Promise.all(users.map(async user => { user.posts = await this.postsService.findByUserId(user.id); return user; })); }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No DataLoader (many DB calls) | N/A (server-side) | Multiple sequential DB calls delay response | Blocks initial paint until all data fetched | [X] Bad |
| With DataLoader (batched calls) | N/A (server-side) | Single batched DB call reduces delay | Faster initial paint due to quicker response | [OK] Good |
DataLoader in a NestJS application?new DataLoader(batchFunction), where batchFunction is a function receiving keys.new DataLoader(keys => batchFunction(keys)). Options B, C, and D use incorrect syntax or call batchFunction immediately.new DataLoader(batchFunction) [OK]async function batchUsers(ids: readonly number[]) {
return ids.map(id => ({ id, name: `User${id}` }));
}await loader.load(2) if loader is created with this batch function?loader.load(2) returns a single user object corresponding to id 2, not an array.async function batchPosts(ids: readonly number[]) {
const posts = await getPostsByIds(ids);
return posts;
}getPostsByIds returns posts unordered, the batch function breaks this contract causing wrong results.posts is not in the same order as ids -> Option APass the test and this pattern moves unknown