Created
February 15, 2017 16:35
-
-
Save augustine-tran/52e19d05f76bf8271179470fd51f98ca to your computer and use it in GitHub Desktop.
Adding pagination to knex.js
This file contains 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 Knex = require('knex'); | |
var Promise = require('bluebird'); | |
Object.assign(Knex.Client.prototype.QueryBuilder.prototype, { | |
paginate(per_page, current_page) { | |
var pagination = {}; | |
var per_page = +per_page || 8; | |
var page = +current_page || 1; | |
if ( page < 1 ) page = 1; | |
var offset = (page - 1) * per_page; | |
return Promise.all([ | |
this.clone().count('* as count').first(), | |
this.offset(offset).limit(per_page) | |
]).then(function(values) { | |
var count = values[0].count; | |
var rows = values[1]; | |
pagination.data = rows; | |
pagination.total = count; | |
pagination.per_page = per_page; | |
pagination.offset = offset; | |
pagination.to = offset + rows.length; | |
pagination.last_page = Math.ceil(count / per_page); | |
pagination.current_page = page; | |
pagination.from = offset; | |
return pagination; | |
}); | |
}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment