-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathpaginator.js
88 lines (69 loc) · 2.29 KB
/
paginator.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
const debug = require('debug')('loopback:mixins:paginator');
const DEFAULT_LIMIT = 10;
const DEFAULT_MAX_LIMIT = 100;
const DEFAUL_NO_MAX_LIMIT = false;
module.exports = function (Model, options = {}) {
debug('Pagintor mixin for model %s', Model.modelName);
Model.getApp((error, app) => {
if (error) {
debug(`Error getting app: ${error}`);
}
let globalOptions = app.get('paginator') || {};
options.limit = options.limit || globalOptions.limit || DEFAULT_LIMIT;
options.maxLimit = options.maxLimit || globalOptions.maxLimit || DEFAULT_MAX_LIMIT;
options.noMaxLimit = options.noMaxLimit || globalOptions.noMaxLimit || DEFAUL_NO_MAX_LIMIT;
});
Model.beforeRemote('find', async (context) => {
if (!context.req.query.page) { return; }
context.args.filter = modifyFilter(context.args.filter, context.req.query.page);
});
Model.afterRemote('find', async (context) => {
if (!context.req.query.page) { return; }
const limit = getLimit(context.args.filter);
const where = context.args.filter.where || null;
const totalItemCount = await Model.count(where);
const totalPageCount = Math.ceil(totalItemCount / limit);
const currentPage = parseInt(context.req.query.page) || 1;
const previousPage = currentPage - 1;
const nextPage = currentPage + 1;
context.result = {
data: context.result,
meta: {
totalItemCount: totalItemCount,
totalPageCount: totalPageCount,
itemsPerPage: limit,
currentPage: currentPage,
}
}
if (nextPage <= totalPageCount) {
context.result.meta.nextPage = nextPage;
}
if (previousPage > 0) {
context.result.meta.previousPage = previousPage;
}
});
function modifyFilter(filter, page) {
const limit = getLimit(filter);
const skip = (page - 1) * limit;
if (!filter) {
filter = {
skip: skip,
limit: limit,
}
return filter;
}
filter.skip = skip;
filter.limit = limit;
return filter;
}
function getLimit(filter) {
if (filter && filter.limit) {
let limit = parseInt(filter.limit);
if (options.maxLimit && !options.noMaxLimit) {
limit = limit > options.maxLimit ? options.maxLimit : limit;
}
return limit;
}
return options.limit;
}
}