Last active
March 8, 2016 16:07
-
-
Save rhys-vdw/d4b403969eda377c0eef to your computer and use it in GitHub Desktop.
Revisions
-
rhys-vdw renamed this gist
Jun 17, 2015 . 1 changed file with 0 additions and 0 deletions.There are no files selected for viewing
File renamed without changes. -
rhys-vdw renamed this gist
Jun 17, 2015 . 1 changed file with 0 additions and 0 deletions.There are no files selected for viewing
File renamed without changes. -
rhys-vdw created this gist
Jun 17, 2015 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,45 @@ 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