Skip to content

Commit

Permalink
Merge 449ad11 into 8e5bdaa
Browse files Browse the repository at this point in the history
  • Loading branch information
parodimatias committed Aug 30, 2023
2 parents 8e5bdaa + 449ad11 commit 779f758
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
8 changes: 6 additions & 2 deletions lib/mongodb.js
Original file line number Diff line number Diff line change
Expand Up @@ -430,21 +430,25 @@ module.exports = class MongoDB {
* @param {import('@janiscommerce/model')} model Model instance
* @returns {Promise<GetTotalsResult>} total, page size, pages and page from the results.
*/
async getTotals(model) {
async getTotals(model, filter) {

if(!model)
throw new MongoDBError('Invalid or empty model', MongoDBError.codes.INVALID_MODEL);

const {
length,
filters = {},
filters: paramsFilters = {},
limit = this.config.limit,
page = 0
} = model.totalsParams || {};

if(length === 0)
return { total: 0, pages: 0 };

const parsedFilters = MongoDBFilters.parseFilters(ObjectIdHelper.ensureObjectIdsForWrite(model, filter || {}), model);

const filters = Object.keys(parsedFilters).length ? parsedFilters : paramsFilters;

try {

/**
Expand Down
28 changes: 28 additions & 0 deletions tests/mongodb.js
Original file line number Diff line number Diff line change
Expand Up @@ -2193,6 +2193,34 @@ describe('MongoDB', () => {

sinon.assert.notCalled(estimatedDocumentCount);
});

it('Should return the totals object for queries with filters though params, specific page and custom limit using countDocuments()', async () => {

const mongodb = new MongoDB(config);

const estimatedDocumentCount = sinon.stub();
const countDocuments = sinon.stub().resolves(4);

const { collection } = mockChain(true, [{ a: 3 }, { a: 4 }], { countDocuments, estimatedDocumentCount });

const model = getModel();
const result = await mongodb.getTotals(model, { status: 'active' });

assert.deepStrictEqual(result, {
total: 4,
pageSize: 500,
page: 0,
pages: 1
});

// Collection no se llama para el get
sinon.assert.calledOnce(collection);
sinon.assert.calledOnceWithExactly(countDocuments, {
status: { $eq: 'active' }
});

sinon.assert.notCalled(estimatedDocumentCount);
});
});

context('When not using filters', () => {
Expand Down

0 comments on commit 779f758

Please sign in to comment.