Skip to content

Instantly share code, notes, and snippets.

@sthawali
Last active August 29, 2015 14:04
Show Gist options
  • Save sthawali/4505ea243cc44231064e to your computer and use it in GitHub Desktop.
Save sthawali/4505ea243cc44231064e to your computer and use it in GitHub Desktop.
Simple server side pagination module for mongodb
'use strict';
/**
* Paginator
*
* 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.
*
*/
exports.paginator = function(db) {
if (!db) {
throw new Error('You are not connected to database server. {db} is missing.');
}
/**
* Options
*/
this.db = db;
this.collection = null;
this.query = {};
this.sort = false;
this.current = 1;
this.recordPerPage = 50;
/**
* Records count && total records
*/
this.recordCount = 0;
this.totalRecords = 0;
/**
* Calculate records data
* @return {object} paginator object with records
*/
var calculatePagedData = function(that, records) {
var totalResult = that.totalRecords;
var recordPerPage = that.recordPerPage;
var current = that.current;
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;
}
/**
* 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);
* var pagination = new Paginator(DATABASE);
*
* pagination.getPaginatedRecords(OPTIONS, CALLBACK_FUNCTION);
*
* Options:
* {
* collection: COLLECTION_NAME, // required
* 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);
* var pagination = new Paginator(db);
*
* pagination.getPaginatedRecords({
* collection: 'users',
* recordPerPage: 10
* }, function(err, data) {
* if(err) {
* return next(err);
* }
*
* // Do stuff with data object
*
* });
*/
this.getPaginatedRecords = function(options, callback) {
var that = this;
/**
* if callback is passed
* @type {function}
*/
if (typeof options === 'function') {
callback = options;
}
/**
* Check for collection exist
*/
if (options.collection) {
this.collection = options.collection;
}
if (!options.collection) {
return callback(new Error('Collection name is required. {collection} is missing from options'));
}
if (options.query) {
this.query = options.query;
}
if (options.sort) {
this.sort = options.sort;
}
if (options.current) {
this.current = options.current;
}
if (options.recordPerPage) {
this.recordPerPage = options.recordPerPage;
}
if (options.totalResult) {
this.totalRecords = options.totalResult;
}
/**
* Collection object
* @type {object}
*/
var collection = this.db[this.collection];
/**
* Prepare base db object
* @type {object}
*/
var base = collection
.find(this.query)
.limit(this.recordPerPage)
.skip(this.skip);
/**
* If sorting then do sort
*/
if (this.sort) {
base.sort(this.sort);
}
/**
* Get records for query
* @param {object} err Error object
* @param {object} records Records for query
* @return {object} Paginated object
*/
var getRecords = function() {
base.toArray(function(err, records) {
if (err) {
return callback(err);
}
that.recordCount = records.length;
callback(calculatePagedData(that, 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);
}
that.totalRecords = count;
getRecords();
});
}
};
};
@detj
Copy link

detj commented Jul 23, 2014

👍 this looks hep!

@sudhanshuraheja
Copy link

whoa! good job boss

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment