forked from nemtsov/express-partial-response
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
39 lines (35 loc) · 1.02 KB
/
index.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
var jsonMask = require('json-mask'),
compile = jsonMask.compile,
filter = jsonMask.filter;
module.exports = function (opt) {
opt = opt || {};
function partialResponse(obj, fields) {
if (!fields) return obj;
return filter(obj, compile(fields));
}
function wrap(orig) {
return function (obj) {
if (obj.toJSON) {
obj = obj.toJSON() // Add support for Bookshelf models
}
var param = this.req.query[opt.query || 'fields'];
if (1 === arguments.length) {
orig(partialResponse(obj, param));
} else if (2 === arguments.length) {
if ('number' === typeof arguments[1]) {
orig(arguments[1], partialResponse(obj, param));
} else {
orig(obj, partialResponse(arguments[1], param));
}
}
};
}
return function (req, res, next) {
if (!res.__isJSONMaskWrapped) {
res.json = wrap(res.json.bind(res));
if (req.jsonp) res.jsonp = wrap(res.jsonp.bind(res));
res.__isJSONMaskWrapped = true;
}
next();
};
};