Skip to content

Commit cf0088c

Browse files
committed
fix: handle edge case in addConstranint
1 parent a65184a commit cf0088c

File tree

2 files changed

+7
-2
lines changed

2 files changed

+7
-2
lines changed

src/mongo/util.ts

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,10 @@ import { rulesToQuery } from '@casl/ability/extra';
33
import { JSONPatch } from 'jsonref';
44
import { ObjectId } from 'mongodb';
55

6+
function haveKeysInCommon(a: any, b: any): boolean {
7+
return !!Object.keys(a).find((k) => (typeof b[k] !== 'undefined' ? k : undefined));
8+
}
9+
610
export function addConstraint(query: any, constraint: any): any {
711
if (!query) {
812
query = {};
@@ -23,13 +27,13 @@ export function addConstraint(query: any, constraint: any): any {
2327
query = { $and: [query, constraint] };
2428
} else if (query.$and && Object.keys(constraint).length > 0) {
2529
const lastCond = query.$and[query.$and.length - 1];
26-
if (lastCond && !(lastCond.$or && constraint.$or) && !(lastCond.$and && constraint.$and)) {
30+
if (lastCond && !(lastCond.$or && constraint.$or) && !(lastCond.$and && constraint.$and) && !haveKeysInCommon(lastCond, constraint)) {
2731
Object.assign(lastCond, constraint);
2832
} else {
2933
query.$and.push(constraint);
3034
}
3135
} else {
32-
if (Object.keys(constraint).find((k) => (typeof query[k] !== 'undefined' ? k : undefined))) {
36+
if (haveKeysInCommon(query, constraint)) {
3337
query = { $and: [query, constraint] };
3438
} else {
3539
Object.assign(query, constraint);

test/ts/mongo.util.test.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@ describe('util', function () {
7373
});
7474
it('should handle multiple constraints on a property producing an $and', function () {
7575
addConstraint({ a: 1 }, { a: 2 }).should.deep.equal({ $and: [{ a: 1 }, { a: 2 }] });
76+
addConstraint({ $and: [{ a: 1 }, { a: 2 }] }, { a: 3 }).should.deep.equal({ $and: [{ a: 1 }, { a: 2 }, { a: 3 }] });
7677
});
7778
});
7879
});

0 commit comments

Comments
 (0)