4 ms·
i'm back too late to edit; I'll just double-reply. These two functions take a foreign key and a function to retrieve the data you're after and return you a data
by beaconstudios 6y ago
i'm back too late to edit; I'll just double-reply. These two functions take a foreign key and a function to retrieve the data you're after and return you a dataloader with the correct indexing applied. Quite nifty, and you'd need the equivalent to both of these eventually.
const oneToOne = (foreign, fn) => new Dataloader(async (keys) => {
const results = await fn(keys);
const index = {};
for(const result of results) {
index[result.get(foreign)] = result;
}
return keys.map(key => key in index ? index[key] : null);
});
const oneToMany = (foreign, fn) => new Dataloader(async (keys) => {
const results = await fn(keys);
const index = {};
for(const result of results) {
const foreignKey = result.get(foreign);
if(!(foreignKey in index)) {
index[foreignKey] = [];
}
index[foreignKey].push(result);
}
return keys.map(key => key in index ? index[key] : []);
});
- agustif 6y agoThanks for such thorough answer! Will keep in mind when looking into dataloader, looks nice.