Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added deep equals to object comparison in handle method to support co…
Browse files Browse the repository at this point in the history
…rrectly mutable entities
oskardudycz committed Oct 27, 2024

Verified

This commit was signed with the committer’s verified signature.
hakonanes Håkon Wiik Ånes
1 parent 5e11545 commit 2c2dc9c
Showing 4 changed files with 60 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/packages/pongo/src/core/collection/pongoCollection.ts
Original file line number Diff line number Diff line change
@@ -14,6 +14,7 @@ import {
} from '@event-driven-io/dumbo';
import { v7 as uuid } from 'uuid';
import {
deepEquals,
expectedVersionValue,
operationResult,
type CollectionOperationOptions,
@@ -370,7 +371,7 @@ export const pongoCollection = <

const result = await handle(existing as T);

if (existing === result)
if (deepEquals(existing as T, result))
return operationResult<PongoHandleResult<T>>(
{
successful: true,
1 change: 1 addition & 0 deletions src/packages/pongo/src/core/index.ts
Original file line number Diff line number Diff line change
@@ -6,3 +6,4 @@ export * from './pongoSession';
export * from './pongoTransaction';
export * from './schema';
export * from './typing';
export * from './utils';
56 changes: 56 additions & 0 deletions src/packages/pongo/src/core/utils/deepEquals.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
export const deepEquals = <T>(left: T, right: T): boolean => {
if (isEquatable(left)) {
return left.equals(right);
}

if (Array.isArray(left)) {
return (
Array.isArray(right) &&
left.length === right.length &&
left.every((val, index) => deepEquals(val, right[index]))
);
}

if (
typeof left !== 'object' ||
typeof right !== 'object' ||
left === null ||
right === null
) {
return left === right;
}

if (Array.isArray(right)) return false;

const keys1 = Object.keys(left);
const keys2 = Object.keys(right);

if (
keys1.length !== keys2.length ||
!keys1.every((key) => keys2.includes(key))
)
return false;

for (const key in left) {
if (left[key] instanceof Function && right[key] instanceof Function)
continue;

const isEqual = deepEquals(left[key], right[key]);
if (!isEqual) {
return false;
}
}

return true;
};

export type Equatable<T> = { equals: (right: T) => boolean } & T;

export const isEquatable = <T>(left: T): left is Equatable<T> => {
return (
left &&
typeof left === 'object' &&
'equals' in left &&
typeof left['equals'] === 'function'
);
};
1 change: 1 addition & 0 deletions src/packages/pongo/src/core/utils/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './deepEquals';

0 comments on commit 2c2dc9c

Please sign in to comment.