Skip to content

Instantly share code, notes, and snippets.

@shrirambalakrishnan
Last active August 1, 2020 19:07
Show Gist options
  • Save shrirambalakrishnan/982b7b9db85710a49cf751e0b76b4664 to your computer and use it in GitHub Desktop.
Save shrirambalakrishnan/982b7b9db85710a49cf751e0b76b4664 to your computer and use it in GitHub Desktop.
const DataLoader = require('dataloader');
const postsLoader = new DataLoader( async (userIds) => {
// Assume, userIds = [ 1, 2 ]
let posts = await Post.findAll( { where: { userId: userIds } } );
// posts = [ {title: "A", userId: 1}, {title: "B", userId: 1}, {title: "C", userId: 2} ]
let postsGroupedByUser = userIds.map ( userId => {
return posts.filter( post => post.userId == userId );
});
// postsGroupedByUser = [
// [
// {title: "A", userId: 1},
// {title: "B", userId: 1}
// ],
// [
// {title: "C", userId: 2}
// ]
// ]
return postsGroupedByUser;
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment