Consider a DataLoader batch function that receives an array of user IDs and returns user objects in the same order.
Given the following batch function:
async function batchUsers(userIds) {
const users = await db.query('SELECT * FROM users WHERE id IN (?)', [userIds]);
return userIds.map(id => users.find(user => user.id === id));
}What will be the output if userIds is [3, 1, 2] and the database returns users in order [{id:1, name:'Alice'}, {id:2, name:'Bob'}, {id:3, name:'Carol'}]?
async function batchUsers(userIds) { const users = await db.query('SELECT * FROM users WHERE id IN (?)', [userIds]); return userIds.map(id => users.find(user => user.id === id)); }
Remember DataLoader expects the batch function to return results in the same order as the keys.
The batch function maps each requested ID to the corresponding user object found in the database result. Since userIds is [3,1,2], the output array matches this order with the correct user objects.
What is the main reason to use DataLoader in a GraphQL API?
Think about performance optimization when fetching data.
DataLoader batches multiple requests for the same resource into a single database query and caches results to avoid duplicate fetching, improving performance.
Which option contains a syntax error in the batch function for DataLoader?
const batchFunction = async (keys) => {
const results = await db.query('SELECT * FROM items WHERE id IN (?)', [keys]);
return keys.map(key => results.find(item => item.id === key));
}Look carefully at the comparison operator inside the find callback.
Option D uses a single equals sign = instead of a comparison operator ===, causing an assignment instead of comparison, which is a syntax error in this context.
You have a DataLoader batch function that receives a large array of keys. Which approach optimizes performance best?
Consider database query limits and parallelism.
Splitting large key arrays into smaller chunks and querying in parallel avoids database query size limits and improves throughput compared to one huge query or many sequential queries.
Given this batch function:
async function batch(keys) {
const rows = await db.query('SELECT * FROM products WHERE id IN (?)', [keys]);
return rows;
}Why might this cause incorrect results when used with DataLoader?
Think about DataLoader's requirement for batch function output order.
DataLoader expects the batch function to return results in the same order as the keys array. Returning rows directly from the database without reordering can cause mismatched results.