Last active
March 8, 2016 16:07
-
-
Save rhys-vdw/d4b403969eda377c0eef 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
Promise = require 'bluebird' | |
defaultPageSize = 20 | |
paginate = (knex) -> (query, paginationOptions, options) -> | |
if query.fetchAll? | |
model = query | |
query = model.query() | |
# Store original query. | |
totalQuery = knex.count().from query.clone().as 'inner' | |
totalPromise = totalQuery.then (rows) -> rows[0].count | |
# Extract options | |
{ page, pageSize, offset, limit } = paginationOptions | |
# Set defaults | |
pageSize ?= defaultPageSize | |
offset ?= 0 | |
page = 1 if not page? or page < 1 | |
# Update vars based on interplay between limit/offset and pagination. | |
page += offset // pageSize | |
# Calculate actual limit and offset to be used in query. (Note that the | |
# natural concept of a page starts from 1 rather than 0.) | |
limit = limit ? pageSize | |
offset += (page - 1) * pageSize | |
query.offset offset | |
query.limit limit if limit > 0 | |
return Promise.all([ | |
model?.fetchAll(options) or query | |
totalPromise | |
]).spread (data, total) -> { | |
pagination: { | |
total, pageSize, offset, limit, page, | |
pageCount: Math.ceil(total / pageSize) | |
}, | |
data | |
} | |
module.exports = paginate |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Is this still your preferred pagination method? Looking into implementing something on my side.