Skip to content

Instantly share code, notes, and snippets.

@pirey
Forked from andremsantos/knex-pagination.js
Last active April 6, 2024 14:40
Show Gist options
  • Save pirey/b5be4bbc8aed08a6bbe6b00af8b02ab5 to your computer and use it in GitHub Desktop.
Save pirey/b5be4bbc8aed08a6bbe6b00af8b02ab5 to your computer and use it in GitHub Desktop.
Adding pagination to knex.js
const config = require('./config')
const knex = require('knex')(config.db)
const QueryBuilder = require('knex/lib/query/builder')
QueryBuilder.prototype.paginate = function ({ limit = 10, page = 1 }) {
const offset = (page - 1) * limit
return Promise.all([
this.clone().count('* as count').first(),
this.offset(offset).limit(limit)
])
.then(([count, data]) => {
const total = count.count
return {
total,
limit,
offset,
from: offset + 1,
to: offset + data.length,
page,
lastPage: Math.ceil(total / limit),
data
}
})
}
knex.queryBuilder = function () {
return new QueryBuilder(knex.client)
}
module.exports = knex
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment