-
-
Save DomenicoColandrea86/44f516e22a75829a0602018f3d7719cc to your computer and use it in GitHub Desktop.
Adding pagination to knex.js
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
module.exports = function(dbConfig) { | |
var knex = require('knex')(dbConfig); | |
var KnexQueryBuilder = require('knex/lib/query/builder'); | |
KnexQueryBuilder.prototype.paginate = function (per_page, current_page) { | |
var pagination = {}; | |
var per_page = per_page || 10; | |
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(([total, rows]) => { | |
var count = total.count; | |
var rows = 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; | |
pagination.data = rows; | |
return pagination; | |
}); | |
}; | |
knex.queryBuilder = function () { | |
return new KnexQueryBuilder(knex.client); | |
}; | |
return knex; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why do we need to re-instantiate knex's querybuilder? (i.e. this code below)
Doesn't changing the prototype for the QueryBuilder affect the existing instance?
And it seems to be working fine without this last part!