-
Notifications
You must be signed in to change notification settings - Fork 13
/
loaders.js
40 lines (34 loc) · 1.04 KB
/
loaders.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
const Tag = require('./models/tag')
const User = require('./models/user')
const Article = require('./models/article')
const Version = require('./models/version')
const DataLoader = require('dataloader')
async function getTags (tagIds) {
return findByIds(tagIds, Tag)
}
async function getUsers (userIds) {
return findByIds(userIds, User)
}
async function getArticles (articleIds) {
return findByIds(articleIds, Article)
}
async function getVersions (versionIds) {
return findByIds(versionIds, Version)
}
async function findByIds(ids, model) {
const items = await model
.find({ _id: { $in: ids } })
.lean()
const itemByIds = items.reduce((acc, item) => {
acc[item._id] = item
return acc
}, {})
// eslint-disable-next-line security/detect-object-injection
return ids.map(id => itemByIds[id])
}
module.exports = {
createTagLoader: () => new DataLoader(getTags),
createUserLoader: () => new DataLoader(getUsers),
createArticleLoader: () => new DataLoader(getArticles),
createVersionLoader: () => new DataLoader(getVersions),
}