From b8824be85b2d6c79de2f73e93b2c699b0a641cc1 Mon Sep 17 00:00:00 2001 From: leguass7 Date: Tue, 5 May 2020 00:32:25 -0300 Subject: [PATCH] improvement: query on using aggregate function --- src/index.js | 17 +++++++++++++++++ test/index.js | 24 ++++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/src/index.js b/src/index.js index 1374b3cf..62cd4d06 100644 --- a/src/index.js +++ b/src/index.js @@ -5,6 +5,7 @@ */ class SequelizePaginate { /** @typedef {import('sequelize').Model} Model */ + /** @typedef {import('sequelize').IncludeOptions} IncludeOptions */ /** * Method to append paginate method to Model. * @@ -45,11 +46,27 @@ class SequelizePaginate { paginate = 25, ...params } = {}) { + /** + * @description Checks if you have required aggregate. + * @function hasAggregate + * @param {Array} 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 }, {}) diff --git a/test/index.js b/test/index.js index 70ff547c..21b07d97 100644 --- a/test/index.js +++ b/test/index.js @@ -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) + }) }) })