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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276 | 1
1
12
1
2
2
2
2
2
2
4
2
1
2
2
2
2
1
2
2
4
2
2
4
2
2
2
2
1
2
2
2
2
2
2
1
2
2
2
1
6
6
6
6
2
6
6
6
6
6
6
6
6
6
6
6
6
6
1
6
6
6
6
6
6
5
1
1
1
6
1
1
5
2
2
2
1
1
1
1
1
1
1
1
1
1
1
1
1
6
6
6
6
6
6
6
6
6
6
6
6
1
6
2
6
6
6
1
1
6
6
6
1
1
1
1
1
1
1
5
3
2
5
5
5
5
5
5
5
1
1
| var async = require('async'),
HttpError = require('http-errors'),
_ = require('lodash'),
clone = require('clone'),
querystring = require('querystring'),
deasync = require('deasync'),
mongoose = require('mongoose');
function encode(obj) {
return querystring.escape(new Buffer(querystring.stringify(obj)).toString('base64'));
}
// equivalent to db.collection.getIndexKeys in mongodb shell
function getIndexKeys(model) {
var indexKeys = [];
var collection = model.collection;
var indexInformation = deasync(collection.indexInformation);
try {
var indexes = indexInformation.call(collection);
_.forEach(indexes, function(index) {
indexKeys.push(_.object(index));
});
} catch(err) {
throw new HttpError(500, 'Cannot retrieve index keys');
}
return indexKeys;
}
function oppositeIndex(index) {
var opposite = clone(index);
_.forEach(opposite, function(direction, key) {
opposite[key] = direction * -1;
});
return opposite;
}
function compoundIndexExists(indexes, index) {
var exists = false, oppositeExists = false,
opposite = oppositeIndex(index);
_.forEach(indexes, function(key) {
if (JSON.stringify(key) === JSON.stringify(index) && !exists) {
exists = true;
} else Iif (JSON.stringify(key) === JSON.stringify(opposite) && !oppositeExists) {
oppositeExists = true;
}
Iif (exists && oppositeExists) {
return false;
}
});
Iif (exists && oppositeExists) {
return 2;
} else Iif (oppositeExists) {
return 1;
} else Eif (exists) {
return true;
} else {
return false;
}
}
function keysInSameOrder(obj1, obj2) {
var arr1 = [],
arr2 = [];
_.forEach(obj1, function(val, key) {
arr1.push(key);
});
_.forEach(obj2, function(val, key) {
arr2.push(key);
});
return JSON.stringify(arr1) === JSON.stringify(arr2);
}
function flipDirections(options) {
_.forEach(options.sortBy, function(direction, key) {
options.sortBy[key] = direction * -1;
});
options.flip = !options.flip;
}
function execPagination(q, callback) {
var _return = {},
after, before;
q.exec(function(err, objects) {
Iif (!objects) {
objects = [];
}
if (q.options.flip) {
objects.reverse();
}
_return.objects = objects;
_return.thisPageCount = objects.length;
Eif (objects.length > 0) {
_return.after = {};
_return.before = {};
after = objects.length - 1;
before = 0;
_.forEach(q.options.sortBy, function(direction, sortKey) {
_return.after[sortKey] = objects[after][sortKey].toString();
_return.before[sortKey] = objects[before][sortKey].toString();
});
_return.after = encode(_return.after);
_return.before = encode(_return.before);
} else {
_return.after = null;
_return.before = null;
}
return callback(err, _return);
});
}
function setPaginateParams(options, model, last, difference) {
Eif (!options.sortBy) {
options.sortBy = {};
}
options.sortBy._id = 1;
options.flip = false;
Iif (_.size(options.sortBy) > 1) {
_.forEach(options.sortBy, function(direction, sortKey) {
options.sortBy[sortKey] = parseInt(direction, 10);
});
_.forEach(options.sortBy, function(direction, sortKey) {
options.sortBy._id = direction; // direction is primary sort key (first key)
return false;
});
}
// if user provides both before and after, decide which one to use
if (difference > 0) {
options.before = undefined;
} else Eif (difference < 0) {
last = false;
options.after = undefined;
} else {
options.before = undefined;
options.after = undefined;
}
if (last) {
flipDirections(options);
return;
}
if (options.after || options.before) {
var hasIndex = compoundIndexExists(getIndexKeys(model), options.sortBy);
Eif (hasIndex) {
if (options.after && keysInSameOrder(options.after, options.sortBy)) {
options.filter = {};
options.after._id = mongoose.Types.ObjectId(options.after._id);
Iif (hasIndex === 1) {
options.filter = {max: options.after, skip: 1};
options.filter.hint = oppositeIndex(options.sortBy);
} else {
options.filter = {min: options.after, skip: 1};
options.filter.hint = clone(options.sortBy);
}
} else Eif (options.before && keysInSameOrder(options.before, options.sortBy)) {
options.filter = {};
options.before._id = mongoose.Types.ObjectId(options.before._id);
Iif (hasIndex === 1) {
options.filter = {min: options.before, skip: 1};
options.filter.hint = oppositeIndex(options.sortBy);
} else {
options.filter = {max: options.before, skip: 1};
options.filter.hint = clone(options.sortBy);
}
flipDirections(options);
}
}
}
}
function paginate(q, fromPageNumber, toPageNumber, resultsPerPage, callback, options) {
var query, skipTo, columns, sortBy, filter, populate, pageJump,
last = options.last == 'true', model = this;
options = options || {};
setPaginateParams(options, model, last, toPageNumber - fromPageNumber);
columns = options.columns || null;
sortBy = options.sortBy || null;
filter = options.filter || null;
populate = options.populate || null;
callback = callback || function() {};
skipTo = (toPageNumber * resultsPerPage) - resultsPerPage;
pageJump = Math.abs(toPageNumber - fromPageNumber);
query = model.find(clone(q));
if (columns) {
query = query.select(columns);
}
if (filter) {
query.setOptions(filter);
}
Eif (sortBy) {
query = query.sort(sortBy);
}
if (populate) {
Iif (Array.isArray(populate)) {
populate.forEach(function(field) {
query = query.populate(field);
});
} else {
query = query.populate(populate);
}
}
query.options.flip = options.flip;
query.options.sortBy = options.sortBy;
if (last) {
model.count(q, function(err, count) {
Iif (err) {
return callback(err);
}
Eif (count % resultsPerPage) {
query = query.limit(count % resultsPerPage);
} else {
query = query.limit(resultsPerPage);
}
execPagination(query, function(err, data) {
Iif (err) {
callback(err);
}
callback(null, toPageNumber, data.before, data.after, data.thisPageCount,
Math.ceil(count / resultsPerPage) || 1, count, data.objects);
});
});
} else {
// fallback to traditional skip when options.after or options.before not given
if (!filter) {
query = query.skip(skipTo);
// go to page current+|N|, |N| > 1
} else Iif (pageJump > 1) {
skipTo = ((pageJump - 1) * resultsPerPage) + filter.skip;
query.setOptions({skip: skipTo});
}
query = query.limit(resultsPerPage);
async.parallel({
results: function(callback) {
execPagination(query, callback);
},
count: function(callback) {
model.count(q, function(err, count) {
callback(err, count);
});
}
}, function(error, data) {
Iif (error) {
return callback(error);
}
callback(null, toPageNumber, data.results.before, data.results.after, data.results.thisPageCount,
Math.ceil(data.count / resultsPerPage) || 1, data.count, data.results.objects);
});
}
}
module.exports = function(schema) {
schema.statics.paginate = paginate;
};
|