Skip to content

Commit

Permalink
add DataLoader
Browse files Browse the repository at this point in the history
  • Loading branch information
hoc081098 committed Sep 27, 2019
1 parent 85d0d9e commit 370ffdf
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 14 deletions.
38 changes: 24 additions & 14 deletions nodejs/graphql/resolvers/merge.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,35 @@
const DataLoader = require('dataloader');

const Event = require('../../models/event');
const User = require('../../models/user');

const { dateToString } = require('../../util/date');

const eventsLoader = new DataLoader(async ids => {
console.log('events', { ids });
const events = await Event.find({ _id: { $in: ids } });
return events.map(transformEvent);
});

const userLoader = new DataLoader(ids => {
console.log('user', { ids });
return User.find({ _id: { $in: ids } }).exec();
});

const findUserById = async id => {
const user = await User.findById(id);
const user = await userLoader.load(id.toString());
return {
...user._doc,
createdEvents: () => findEventsByIds(user.createdEvents),
createdEvents: () => eventsLoader.loadMany(user.createdEvents.map(id => id.toString())),
};
};

const findEventById = async id => {
const event = await Event.findById(id);
return transformEvent(event);
}

const findEventsByIds = async ids => {
const events = await Event.find({ _id: { $in: ids } });
return events.map(transformEvent);
}
const findEventById = id => eventsLoader.load(id.toString());

/**
*
* @param {*} event
*/
const transformEvent = event => {
return {
...event._doc,
Expand All @@ -29,6 +38,10 @@ const transformEvent = event => {
};
}

/**
*
* @param {*} booking
*/
const transformBooking = booking => {
return {
...booking._doc,
Expand All @@ -40,9 +53,6 @@ const transformBooking = booking => {
}

module.exports = {
findUserById,
findEventById,
findEventsByIds,
transformEvent,
transformBooking,
}
5 changes: 5 additions & 0 deletions nodejs/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions nodejs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"dependencies": {
"bcrypt": "^3.0.6",
"cors": "^2.8.5",
"dataloader": "^1.4.0",
"express": "^4.17.1",
"express-graphql": "^0.9.0",
"graphql": "^14.4.2",
Expand Down

0 comments on commit 370ffdf

Please sign in to comment.