Skip to content

Commit

Permalink
Merge de49cff into 6cd666d
Browse files Browse the repository at this point in the history
  • Loading branch information
paezraphael committed Dec 5, 2019
2 parents 6cd666d + de49cff commit d8e907e
Showing 1 changed file with 14 additions and 3 deletions.
17 changes: 14 additions & 3 deletions src/Database/MonkeyPatch.js
Expand Up @@ -17,6 +17,7 @@
const _ = require('lodash')
const KnexQueryBuilder = require('knex/lib/query/builder')
const excludeAttrFromCount = ['order', 'columns', 'limit', 'offset']
const excludeSubAttrFromCount = ['join', 'order', 'columns', 'group', 'limit', 'offset', 'where']
const util = require('../../lib/util')

const _from = KnexQueryBuilder.prototype.from
Expand Down Expand Up @@ -129,6 +130,7 @@ KnexQueryBuilder.prototype.forPage = function (page = 1, perPage = 20) {
KnexQueryBuilder.prototype.paginate = async function (page = 1, perPage = 20) {
const countByQuery = this.clone()

const subByQuery = this.clone()
/**
* Copy the subQuery fn to the clone query. This will make sure
* that build uses the extended query builder methods on the
Expand All @@ -141,17 +143,26 @@ KnexQueryBuilder.prototype.paginate = async function (page = 1, perPage = 20) {
*/
page = Number(page)
perPage = Number(perPage)

/**
* Remove statements that will make things bad with count
* query, for example `orderBy`
*/

countByQuery._statements = _.filter(countByQuery._statements, (statement) => {
return excludeAttrFromCount.indexOf(statement.grouping) < 0
})

const counts = await countByQuery.count('* as total')
subByQuery._statements = _.filter(subByQuery._statements, (statement) => {
return excludeSubAttrFromCount.indexOf(statement.grouping) < 0
})

const counts = await subByQuery
.count('* as total')
.from({
main: countByQuery.select(this.client.raw("'total'"))
})
const total = _.get(counts, '0.total', 0)

const data = total === 0 ? [] : await this.forPage(page, perPage)

return {
Expand Down Expand Up @@ -180,7 +191,7 @@ KnexQueryBuilder.prototype.paginate = async function (page = 1, perPage = 20) {
* ```
*/
function generateAggregate (aggregateOp, defaultColumnName = undefined) {
let funcName = `get${_.upperFirst(aggregateOp)}`
const funcName = `get${_.upperFirst(aggregateOp)}`

/**
* Do not re-add the method if exists
Expand Down

0 comments on commit d8e907e

Please sign in to comment.