-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
executable file
·96 lines (90 loc) · 2.56 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
module.exports = function (app, options) {
var remotes = app.remotes();
const convertQuery = function (req) {
if (req.query) {
const filter = {
skip: 0,
limit: 50,
order: '',
where: {}
};
if (req.query.filter) {
try {
const fields = JSON.parse(req.query.filter);
for (let field in fields) {
if (fields.hasOwnProperty(field)) {
if (field === 'where') {
// This query object is correctly parsed, do nothing
return null;
}
if (Array.isArray(fields[field])) {
filter.where[field] = {
'inq': fields[field]
};
} else {
filter.where[field] = fields[field];
}
}
}
} catch (e) {
}
}
if (req.query.sort) {
try {
filter.order = JSON.parse(req.query.sort).join(' ');
} catch (e) {
}
}
if (req.query.range) {
try {
const range = JSON.parse(req.query.range);
filter.skip = range[0];
filter.limit = range[1] - range[0] + 1;
} catch (e) {
}
}
return filter;
}
return null;
};
// Set Content-Range for all search requests
const applyRange = function (ctx, next) {
if (!ctx.res._headerSent) {
let filter;
let limit = 50;
let skip = 0;
if (ctx.args && ctx.args.filter) {
filter = ctx.args.filter.where;
limit = ctx.args.filter.limit;
skip = ctx.args.filter.skip;
}
let name = this.pluralModelName || this.name;
this.count(filter, function (err, count) {
const last = Math.min(skip + limit, count);
ctx.res.set('Access-Control-Expose-Headers', 'Content-Range');
ctx.res.set('Content-Range', `${name.toLowerCase()} ${skip}-${last}/${count}`);
next();
});
} else {
next();
}
};
var pattern = options && Array.isArray(options.pattern) ? options.pattern : ['*.find'];
for (var i=pattern.length-1; i>=0; i--) {
remotes.after(pattern[i], applyRange);
}
app.middleware('routes:before', function (req, res, next) {
const filter = convertQuery(req);
if (filter) {
if (req.query) {
delete req.query.filter;
delete req.query.sort;
delete req.query.range;
req.query = {...req.query, filter: JSON.stringify(filter)};
} else {
req.query = {filter: JSON.stringify(filter)};
}
}
next();
});
};