-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
174 lines (156 loc) · 4.86 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
'use strict';
/*jshint esversion: 6 */
const DEFAULT_LIMIT = 10;
const DEFAULT_PAGE = 1;
/**
* Exports a plugin to pass into the bookshelf instance, i.e.:
*
* import config from './knexfile';
* import knex from 'knex';
* import bookshelf from 'bookshelf';
*
* const ORM = bookshelf(knex(config));
*
* ORM.plugin(require('./simplepaginate.plugin'));
*
* export default ORM;
*
* The plugin attaches one instance method to the bookshelf
* Model object: simplePaginate.
*
* Model#simplepaginate works like Model#fetchAll, but returns a single page of
* results instead of all results, as well as the pagination information
*
* See methods below for details.
*/
module.exports = function simplePaginationPlugin(bookshelf) {
const Model = bookshelf.Model;
/**
* @method Model#fetchSimplePaginate
* @belongsTo Model
*
* Similar to {@link Model#fetchAll}, but fetches a single page of results
* as specified by the limit (page size) and offset or page number.
*
* Any options that may be passed to {@link Model#fetchAll} may also be passed
* in the options to this method.
*
* To perform pagination, you may include *either* an `page` and `limit`
*
* By default, with no parameters or missing parameters, `fetchSimplePaginate` will use an
* options object of `{page: 1, limit: 10}`
*
*
* Below is an example showing the user of a JOIN query with sort/ordering,
* pagination, and related models.
*
* @example
*
* Car
* .query(function (qb) {
* qb.innerJoin('manufacturers', 'cars.manufacturer_id', 'manufacturers.id');
* qb.groupBy('cars.id');
* qb.where('manufacturers.country', '=', 'Sweden');
* })
* .simplepaginate({
* limit: 15, // Defaults to 10 if not specified
* page: 3, // Defaults to 1 if not specified
* withRelated: ['engine'] // Passed to Model#fetchAll
* })
* .then(function (results) {
* console.log(results); // Paginated results object with metadata example below
* })
*
* // Pagination results:
*
* {
* models: [<Car>], // Regular bookshelf Collection
* // other standard Collection attributes
* ...
* meta: {
* pagination: {
* count: 53, // Total number of rows found for the query after pagination
* per_page: 15, // The requested number of rows per page
* current_page: 3, // The requested page number
* links: {
* previous:
* next:
* }
* }
* }
* }
*
* @param options {object}
* The pagination options, plus any additional options that will be passed to
* {@link Model#fetchAll}
* @returns {Promise<Model|null>}
*/
function simplePaginate(options = {}) {
function objectWithoutProperties(obj, keys) {
var target = {};
for (var i in obj) {
if (keys.indexOf(i) >= 0) continue;
if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
target[i] = obj[i];
}
return target;
}
function ensureIntWithDefault(val, def) {
if (!val) {
return def;
}
val = parseInt(val);
if (Number.isNaN(val)) {
return def;
}
return val;
}
const {
page,
limit,
} = options;
const _limit = ensureIntWithDefault(limit, DEFAULT_LIMIT);
let _page = ensureIntWithDefault(page, DEFAULT_PAGE);
const fetchMethodName = this instanceof Model ? 'fetchAll' : 'fetch';
const fetchOptions = objectWithoutProperties(options, ['page', 'limit', 'offset']);
const paginate = () => {
return this.clone().query((qb) => {
qb.limit.apply(qb, [_limit + 1]);
qb.offset.apply(qb, [(_page - 1) * _limit]);
})[fetchMethodName](fetchOptions);
};
const total = () => {
return this.clone().query((qb) => {
qb.count('* as total');
})[fetchMethodName](fetchOptions);
}
return paginate().then((datas) => {
let data = datas
return total().then((total) => {
const hasNextPage = data.length === _limit + 1;
const totals = total.toJSON()[0].total;
return {
data: data.slice(0, _limit),
meta: {
pagination: {
count_total: totals,
page_total: Math.ceil(totals / _limit),
count_per_page: hasNextPage ? _limit : data.length,
per_page: _limit,
current_page: _page,
links: {
previous: _page > 1 ? _page - 1 : null,
next: hasNextPage ? _page + 1 : null,
}
},
}
};
});
});
}
bookshelf.Model.prototype.simplePaginate = simplePaginate;
bookshelf.Model.simplePaginate = function (...args) {
return this.forge().simplePaginate(...args);
};
bookshelf.Collection.prototype.simplePaginate = simplePaginate;
};