mongoose-cursor-pagination
Version:
Mongoose cursor-based pagination.
107 lines (84 loc) • 2.79 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports.default = paginationPlugin;
function paginationPlugin(schema, pluginOptions) {
pluginOptions = pluginOptions || {};
var minLimit = +pluginOptions.minLimit || 1;
var maxLimit = +pluginOptions.maxLimit || 100;
var defaultOptions = {
key: pluginOptions.key || '_id',
lean: pluginOptions.lean || false,
limit: +pluginOptions.limit || 20,
sort: {}
};
schema.statics.paginate = function (query, options, callback) {
query = query || {};
options = options || {};
options.limit = +options.limit || defaultOptions.limit;
options = _extends({}, defaultOptions, options);
if (options.limit > maxLimit || options.limit < minLimit) {
options.limit = defaultOptions.limit;
}
var _options = options,
key = _options.key,
select = _options.select,
populate = _options.populate,
lean = _options.lean,
limit = _options.limit,
sort = _options.sort;
var reverse = false;
if (options.startingAfter || options.endingBefore) {
query[key] = {};
if (options.endingBefore) {
query[key] = { $lt: options.endingBefore };
if (sort[key] > 0) {
sort[key] = -1;
reverse = true;
}
} else {
query[key] = { $gt: options.startingAfter };
if (sort[key] <= 0) {
sort[key] = 1;
reverse = true;
}
}
}
var promise = this.find().where(query).select(select).sort(sort).limit(limit + 1).lean(lean);
if (populate) {
[].concat(populate).forEach(function (item) {
return promise.populate(item);
});
}
return new Promise(function (resolve, reject) {
return promise.exec(function (error, items) {
if (error) {
if (typeof callback === 'function') {
setImmediate(function () {
return callback(error);
});
}
return reject(error);
}
items = items || [];
var hasMore = items.length === limit + 1;
if (hasMore) {
items.pop();
}
items = reverse ? items.reverse() : items;
var results = {
items: items,
hasMore: hasMore
};
if (typeof callback === 'function') {
setImmediate(function () {
return callback(null, results);
});
}
return resolve(results);
});
});
};
}