Skip to content

Commit

Permalink
Docs: Improve DataLoader example from O(n²) to O(n) (#7589)
Browse files Browse the repository at this point in the history
  • Loading branch information
ceolinrenato committed May 30, 2023
1 parent 940d1f9 commit bcf5eea
Showing 1 changed file with 7 additions and 1 deletion.
8 changes: 7 additions & 1 deletion docs/source/data/fetching-data.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,13 @@ class ProductsDataSource {

private batchProducts = new DataLoader(async (ids) => {
const productList = await this.dbConnection.fetchAllKeys(ids);
return ids.map((id) => productList.find((product) => product.id === id));
// Dataloader expects you to return a list with the results ordered just like the list in the arguments were
// Since the database might return the results in a different order the following code sorts the results accordingly
const productIdToProductMap = productList.reduce((mapping, product) => {
mapping[product.id] = product;
return mapping;
}, {});
return ids.map((id) => productIdToProductMap[id]);
});

async getProductFor(id) {
Expand Down

0 comments on commit bcf5eea

Please sign in to comment.