-
-
Save pirey/b5be4bbc8aed08a6bbe6b00af8b02ab5 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
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