Skip to content

Instantly share code, notes, and snippets.

@sthawali
Last active August 29, 2015 14:04
Show Gist options
  • Save sthawali/34bac0367308e9dc2eb0 to your computer and use it in GitHub Desktop.
Save sthawali/34bac0367308e9dc2eb0 to your computer and use it in GitHub Desktop.
Simple server side pagination module for mongoose
'use strict';
/**
* Paginator Plugin(for mongoose)
*
* The MIT License (MIT)
* Copyright (c) 2014 Shekhar R. Thawali<shekhar@leftshift.io>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
/**
* Options
*/
var query, sort, current = 1,
recordPerPage = 50,
recordCount = 0,
totalRecords = 0;
/**
* Get records with paginator object
* @param {object} options Options object
* @param {function} callback Callback function
* @return {object} paginator object with records
*
* Usage:
*
* var paginator = require(PATH_OF_PAGINATOR);
* Schema.plugin(paginator);
*
* Schema.paginate(OPTIONS, CALLBACK_FUNCTION);
*
* Options:
* {
* query: QUERY_TO_FETCH_RECORDS // optional
* sort: SORTING_ORDER, // optional. Format is {KEY: 1/-1}
* current: CURRENT_PAGE_NUMBER, // default 1
* recordPerPage: RECORD_PER_PAGE // default 50,
* totalResult: TOTAL_RESULTS
* }
*
* Callback Function:
* function(err, paginatedData);
*
* Response:
* {
* current: CURRENT_PAGE_NUMBER,
* previous: PRIVIOUS_PAGE_NUMBER,
* next: NEXT_PAGE_NUMBER,
* first: FIRST_PAGE_NUMBER,
* last: LAST_PAGE_NUMBER,
* totalResult: TOTAL_RECORDS_COUNT,
* pageCount: TOTAL_PAGES_COUNT,
* records: RECORDS_ARRAY
* }
*
* Example:
*
* var paginator = require(./paginator);
* Schema.plugin(paginator);
*
* Schema.paginate({
* recordPerPage: 10
* }, function(err, data) {
* if(err) {
* return next(err);
* }
*
* // Do stuff with data object
*
* });
*/
function paginator(options, callback) {
/**
* if callback is passed
* @type {function}
*/
if (typeof options === 'function') {
callback = options;
}
if (options.query) {
query = options.query;
}
if (options.sort) {
sort = options.sort;
}
if (options.current) {
current = options.current;
}
if (options.recordPerPage) {
recordPerPage = options.recordPerPage;
}
if (options.totalResult) {
totalRecords = options.totalResult;
}
/**
* Collection object
* @type {object}
*/
var collection = this;
/**
* Prepare base db object
* @type {object}
*/
var base = collection
.find(query)
.limit(recordPerPage)
.skip((current - 1) * recordPerPage);
/**
* If sorting then do sort
*/
if (sort) {
base.sort(sort);
}
/**
* Get records for query
* @param {object} err Error object
* @param {object} records Records for query
* @return {object} Paginated object
*/
var getRecords = function() {
base.exec(function(err, records) {
if (err) {
return callback(err);
}
this.recordCount = records.length;
callback(null, calculatePagedData(records));
});
};
if (this.totalResult) {
return getRecords();
} else {
/**
* Get total records count for query
* @param {object} err Error object
* @param {Number} count Total records count
* @return {Number} Total number of records
*/
collection.count(this.query, function(err, count) {
if (err) {
return callback(err);
}
this.totalRecords = count;
getRecords();
});
}
};
/**
* Calculate page data
* @param {object} records Records array
* @return {object} paginator object with records
*/
function calculatePagedData(records) {
var pageCount;
/**
* Basic result object
* @type {Object}
*/
var result = {
current: current,
previous: null,
next: null,
first: null,
last: null,
totalResult: totalResult,
pageCount: null,
records: records
};
/**
* Return if recordPerPage negative
*/
if (recordPerPage <= 0) {
return result;
}
/**
* Calculate page count
* @type {Number}
*/
pageCount = Math.ceil(totalResult / recordPerPage);
result.pageCount = pageCount;
/**
* Return if page count is less than 2
*/
if (pageCount < 2) {
return result;
}
/**
* Update current value if current > pageCount
*/
if (current > pageCount) {
current = pageCount;
result.current = current;
}
/**
* Set first and previous
*/
if (current > 1) {
result.first = 1;
result.previous = current - 1;
}
/**
* Set last and next
*/
if (current < pageCount) {
result.last = pageCount;
result.next = current + 1;
}
/**
* Return final result object
*/
return result;
};
/**
* Export plugin
* @param {object} schema Collection Schema
* @return {function} paginator function
*/
module.exports = function(schema) {
schema.statics.paginate = paginator;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment