Skip to content

Commit

Permalink
fix(pagination): convert pagination params to safe int
Browse files Browse the repository at this point in the history
paginations params are accessed via query string resulting in strings, paginate internally converts
them to safe integer
  • Loading branch information
thetutlage committed Jul 28, 2016
1 parent 738db0c commit ec7db37
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 7 deletions.
14 changes: 8 additions & 6 deletions src/Database/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ require('harmony-reflect')
const knex = require('knex')
const util = require('../../lib/util')
const co = require('co')
const _ = require('lodash')

/**
* here we store connection pools, created by database provider. It is
Expand Down Expand Up @@ -297,24 +298,25 @@ Database.forPage = function (page, perPage) {
* @public
*/
Database.paginate = function * (page, perPage, countByQuery) {
perPage = perPage || 20
util.validatePage(page)
const parsedPerPage = _.toSafeInteger(perPage) || 20
const parsedPage = _.toSafeInteger(page)
util.validatePage(parsedPage)
/**
* first we count the total rows before making the actual
* actual for getting results
* query for getting results
*/
countByQuery = countByQuery || this.clone().count('* as total')
const count = yield countByQuery
if (!count[0] || parseInt(count[0].total, 10) === 0) {
return util.makePaginateMeta(0, page, perPage)
return util.makePaginateMeta(0, parsedPage, parsedPerPage)
}

/**
* here we fetch results and set meta data for paginated
* results
*/
const results = yield this.forPage(page, perPage)
const resultSet = util.makePaginateMeta(parseInt(count[0].total, 10), page, perPage)
const results = yield this.forPage(parsedPage, parsedPerPage)
const resultSet = util.makePaginateMeta(parseInt(count[0].total, 10), parsedPage, parsedPerPage)
resultSet.data = results
return resultSet
}
Expand Down
2 changes: 1 addition & 1 deletion test/unit/database.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ describe('Database provider', function () {
yield Database.table('users').paginate()
expect(true).to.equal(false)
} catch (e) {
expect(e.message).to.match(/page parameter is required/)
expect(e.message).to.match(/cannot paginate results for page less than 1/)
}
})

Expand Down

0 comments on commit ec7db37

Please sign in to comment.