Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save DomenicoColandrea86/44f516e22a75829a0602018f3d7719cc to your computer and use it in GitHub Desktop.
Save DomenicoColandrea86/44f516e22a75829a0602018f3d7719cc to your computer and use it in GitHub Desktop.
Adding pagination to knex.js
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;
}
@kerdany
Copy link

kerdany commented Nov 30, 2018

Why do we need to re-instantiate knex's querybuilder? (i.e. this code below)

knex.queryBuilder = function () {
  return new KnexQueryBuilder(knex.client);
};

Doesn't changing the prototype for the QueryBuilder affect the existing instance?
And it seems to be working fine without this last part!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment