Skip to content

Commit

Permalink
fix(core): ensure no duplicates exist in checks/indexes/hooks
Browse files Browse the repository at this point in the history
Related: #4733
  • Loading branch information
B4nan committed Sep 24, 2023
1 parent 8ddaa93 commit fb523c8
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 0 deletions.
7 changes: 7 additions & 0 deletions packages/core/src/typings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,13 @@ export class EntityMetadata<T = any> {
this.selfReferencing = this.relations.some(prop => [this.className, this.root.className].includes(prop.type));
this.hasUniqueProps = this.uniques.length + this.uniqueProps.length > 0;
this.virtual = !!this.expression;
this.checks = Utils.removeDuplicates(this.checks);
this.indexes = Utils.removeDuplicates(this.indexes);
this.uniques = Utils.removeDuplicates(this.uniques);

for (const hook of Object.keys(this.hooks)) {
this.hooks[hook] = Utils.removeDuplicates(this.hooks[hook]);
}

if (this.virtual) {
this.readonly = true;
Expand Down
13 changes: 13 additions & 0 deletions packages/core/src/utils/Utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -862,6 +862,19 @@ export class Utils {
}, [] as T[]);
}

static removeDuplicates<T>(items: T[]): T[] {
const ret: T[] = [];
const contains = (arr: unknown[], val: unknown) => !!arr.find(v => equals(val, v));

for (const item of items) {
if (!contains(ret, item)) {
ret.push(item);
}
}

return ret;
}

static randomInt(min: number, max: number): number {
return Math.round(Math.random() * (max - min)) + min;
}
Expand Down
5 changes: 5 additions & 0 deletions tests/Utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -548,6 +548,11 @@ describe('Utils', () => {
expect(Utils.hasObjectKeys({ a: 'a', __proto__: null })).toEqual(true);
});

test('removeDuplicates', () => {
expect(Utils.removeDuplicates(['foo', 'bar', 'foo', 'bar2'])).toEqual(['foo', 'bar', 'bar2']);
expect(Utils.removeDuplicates([{ v: 'foo' }, { v: 'bar' }, { v: 'foo' }, { v: 'bar2' }])).toEqual([{ v: 'foo' }, { v: 'bar' }, { v: 'bar2' }]);
});

afterAll(async () => orm.close(true));

});

0 comments on commit fb523c8

Please sign in to comment.