Skip to content

Instantly share code, notes, and snippets.

@alexandrebodin
Created September 1, 2016 07:58
Show Gist options
  • Save alexandrebodin/6e43012234abafceb6437051c8cca141 to your computer and use it in GitHub Desktop.
Save alexandrebodin/6e43012234abafceb6437051c8cca141 to your computer and use it in GitHub Desktop.
dataloader batching without caching
import DataLoader from 'dataloader';
const getBatchUsers = (ids = []) => {
// runs sth like
// SELECT * FROM users WHERE id IN (:ids)
};
// cache is disabled
const userLoader = new DataLoader(getBatchUsers, {cache: false});
// Now I'm looping let's say over a list of contacts
const contacts = [
{
id: 1,
userId: 1
},
{
id: 2,
userId: 1
},
{
id: 3,
userId: 1
}
];
const promises = contacts.map(contact => {
return userLoader.load(contact.userId)
.then(user => ({
...contact,
user
}));
});
Promise.all(promises)
.then(contacts => {
// I get all my contacts with users loaded
});
// The issue here is that multiple contacts
// have the same userId and when disabling
// cache the getBatchUsers will be called with [1, 1, 1];
// Basically this will break DataLoader because the query
// will only return one user instead of 3 (which DataLoader doesn't accept)
// The behaviour I expected was getBatchUsers to get called with [1] only
// It would required to implement a distinct key batching
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment