Skip to content

Instantly share code, notes, and snippets.

@rhys-vdw
Last active March 8, 2016 16:07
Show Gist options
  • Select an option

  • Save rhys-vdw/d4b403969eda377c0eef to your computer and use it in GitHub Desktop.

Select an option

Save rhys-vdw/d4b403969eda377c0eef to your computer and use it in GitHub Desktop.

Revisions

  1. rhys-vdw renamed this gist Jun 17, 2015. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. rhys-vdw renamed this gist Jun 17, 2015. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  3. rhys-vdw created this gist Jun 17, 2015.
    45 changes: 45 additions & 0 deletions gistfile1.coffee
    Original 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