Skip to content

Instantly share code, notes, and snippets.

@andremsantos
Last active March 4, 2022 12:36
Show Gist options
  • Save andremsantos/33781f39444efddbf619514104c55f7d to your computer and use it in GitHub Desktop.
Save andremsantos/33781f39444efddbf619514104c55f7d 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;
}
@fuciktomas
Copy link

Hi,
I'm try this with knex 0.20.14 and i got error:
TypeError: Cannot assign to read only property 'queryBuilder'
on the line:
knex.queryBuilder = function queryBuilder()

I changed this to:
knex.context.queryBuilder = function queryBuilder()
and now it works.

@EmmanDizon
Copy link

EmmanDizon commented Mar 4, 2022

Place it inside whenever folder name u want, in my case, under util folder
util / search.js

class Search {
constructor(query, queryString) {
this.query = query;
this.queryString = queryString;
this.tableName = this.query.and._single.table;
}
pagination(resPerPage) {
let { queryString, query, tableName } = this;

let { page } = queryString;
if (page < 1) page = 1;
let offset = (page - 1) * resPerPage;

query
  .select("name", "price", "description", "ratings", "stock")
  .from(`${tableName}`)
  .offset(offset)
  .limit(resPerPage);

return this;

}
}

module.exports = SearchQuery;

on the other part:
// under the controller folder, create a file. "in my case, it is product.js"

const query = require("../config/database/database"); // this is came from knex configuration
const SearchQuery = require("../utils/searchQuery");

exports.getProducts = catchAsyncErrors(async (req, res, next) => {
const resPerPage = 5;
const search = new SearchQuery(query("products"), req.query)
.pagination(resPerPage);

const products = await search.query;
res.status(200).json({
success: true,
products,
});
});

this is working. kindly see screenshot below.
page 1
page 2

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