This repository has been archived by the owner on Feb 4, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
counts.js
49 lines (43 loc) · 1.43 KB
/
counts.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
41
42
43
44
45
46
47
48
49
module.exports = function Counts (Model) {
'use strict';
Model.afterRemote('findById', injectCounts);
Model.afterRemote('findOne', injectCounts);
Model.afterRemote('find', injectCounts);
function injectCounts (ctx, unused, next) {
var resources = ctx.result;
if (resources == null) return next();
var relations = extractRelationCounts(ctx);
if (!Array.isArray(resources)) resources = [resources];
if (!relations.length || !resources.length) {
return next();
}
fillCounts(relations, resources).then(function () {
return next();
}, function () {
return next();
});
}
function extractRelationCounts (ctx) {
var filter;
if (!ctx.args || !ctx.args.filter) return [];
if (typeof ctx.args.filter === 'string') {
filter = JSON.parse(ctx.args.filter);
} else {
filter = ctx.args.filter;
}
var relations = filter && filter.counts;
if (!Array.isArray(relations)) relations = [relations];
return relations.filter(function (relation) {
return Model.relations[relation] && Model.relations[relation].type.startsWith('has');
});
}
function fillCounts (relations, resources) {
return Promise.all(resources.map(function (resource) {
return Promise.all(relations.map(function (relation) {
return resource[relation].count().then(function (count) {
resource[relation + 'Count'] = count;
});
}));
}));
}
};