Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

improvement: query on using aggregate function #315

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
*/
class SequelizePaginate {
/** @typedef {import('sequelize').Model} Model */
/** @typedef {import('sequelize').IncludeOptions} IncludeOptions */
/**
* Method to append paginate method to Model.
*
Expand Down Expand Up @@ -45,11 +46,27 @@ class SequelizePaginate {
paginate = 25,
...params
} = {}) {
/**
* @description Checks if you have required aggregate.
* @function hasAggregate
* @param {Array<IncludeOptions>} includeKey - Include option.
* @returns {boolean} - Has aggregate.
* @example
* hasAggregate({ model: Model }) // false
* hasAggregate({ model: Model, required: true }) // false
*/
const hasAggregate = includeKey => {
return !!includeKey.filter(inc => !!(inc && inc.required)).length > 0
}

const options = Object.assign({}, params)
const countOptions = Object.keys(options).reduce((acc, key) => {
if (!['order', 'attributes', 'include'].includes(key)) {
// eslint-disable-next-line security/detect-object-injection
acc[key] = options[key]
} else if (key === 'include') {
// eslint-disable-next-line security/detect-object-injection
if (hasAggregate(options[key])) acc[key] = options[key]
}
return acc
}, {})
Expand Down
24 changes: 24 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -123,5 +123,29 @@ describe('sequelizePaginate', () => {
expect(pages).to.equal(3)
expect(total).to.equal(11)
})

it('should paginate with aggregate required', async () => {
const { docs, pages, total } = await Author.paginate({
include: [{ model: Book, where: { name: 'book100' }, required: true }],
order: [['id']]
})
expect(docs).to.be.an('array')
expect(docs.length).to.equal(0)
expect(pages).to.equal(0)
expect(total).to.equal(0)
})

it('should paginate with aggregate not required', async () => {
const { docs, pages, total } = await Author.paginate({
include: [{ model: Book, where: { name: 'book100' }, required: false }],
order: [['id']]
})
expect(docs).to.be.an('array')
expect(docs.length).to.equal(25)
expect(docs[0].books).to.be.an('array')
expect(docs[0].books.length).to.equal(0)
expect(pages).to.equal(4)
expect(total).to.equal(99)
})
})
})