test for circular references

This commit is contained in:
Marc-Roig 2023-01-03 12:21:40 +01:00
parent 2528ae5637
commit 26fba9f4be
2 changed files with 63 additions and 36 deletions

View File

@ -45,4 +45,20 @@ describe('sortConnectArray', () => {
'There was a problem connecting relation with id 1 at position {"after":2}. The relation with id 2 needs to be connected first.' 'There was a problem connecting relation with id 1 at position {"after":2}. The relation with id 2 needs to be connected first.'
); );
}); });
test('error with circular references', () => {
const sortConnect = () =>
sortConnectArray(
[
{ id: 2, position: { after: 1 } },
{ id: 3, position: { after: 1 } },
{ id: 1, position: { after: 3 } },
],
[]
);
expect(sortConnect).toThrowError(
'A circular reference was found in the connect array. One relation is trying to connect before/after another one that is trying to connect before/after it'
);
});
}); });

View File

@ -44,6 +44,7 @@ const sortConnectArray = (connectArr, initialArr = [], strictSort = true) => {
if (!needsSorting) return connectArr; if (!needsSorting) return connectArr;
// Iterate over connectArr and populate sortedConnect // Iterate over connectArr and populate sortedConnect
try {
connectArr.forEach((rel, idx) => { connectArr.forEach((rel, idx) => {
const pushRelation = (rel) => { const pushRelation = (rel) => {
sortedConnect.push(rel); sortedConnect.push(rel);
@ -85,6 +86,16 @@ const sortConnectArray = (connectArr, initialArr = [], strictSort = true) => {
computeRelation(rel); computeRelation(rel);
}); });
} catch (err) {
// If it is a RangeError, there is a circular dependency in the connect array.
if (err instanceof RangeError)
throw new InvalidRelationError(
'A circular reference was found in the connect array. ' +
'One relation is trying to connect before/after another one that is trying to connect before/after it'
);
throw err;
}
return sortedConnect; return sortedConnect;
}; };