Created
March 2, 2016 05:33
-
-
Save prashcr/10065c65caf55956e3eb to your computer and use it in GitHub Desktop.
Poor man's knex/bookshelf pagination
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Promise, defaultPageSize, paginate; | |
Promise = require('bluebird'); | |
defaultPageSize = 20; | |
paginate = function(knex) { | |
return function(query, paginationOptions, options) { | |
var limit, model, offset, page, pageSize, totalPromise, totalQuery; | |
if (query.fetchAll != null) { | |
model = query; | |
query = model.query(); | |
} | |
totalQuery = knex.count().from(query.clone().as('inner')); | |
totalPromise = totalQuery.then(function(rows) { | |
return rows[0].count; | |
}); | |
page = paginationOptions.page, pageSize = paginationOptions.pageSize, offset = paginationOptions.offset, limit = paginationOptions.limit; | |
if (pageSize == null) { | |
pageSize = defaultPageSize; | |
} | |
if (offset == null) { | |
offset = 0; | |
} | |
if ((page == null) || page < 1) { | |
page = 1; | |
} | |
page += Math.floor(offset / pageSize); | |
limit = limit != null ? limit : pageSize; | |
offset += (page - 1) * pageSize; | |
query.offset(offset); | |
if (limit > 0) { | |
query.limit(limit); | |
} | |
return Promise.all([(model != null ? model.fetchAll(options) : void 0) || query, totalPromise]).spread(function(data, total) { | |
return { | |
pagination: { | |
total: total, | |
pageSize: pageSize, | |
offset: offset, | |
limit: limit, | |
page: page, | |
pageCount: Math.ceil(total / pageSize) | |
}, | |
data: data | |
}; | |
}); | |
}; | |
}; | |
module.exports = paginate; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment