Skip to content

Commit

Permalink
Fix merging array-like objects (#659)
Browse files Browse the repository at this point in the history
* test case

* fix merging array-like object

* Delete pnpm-lock.yaml

* import array utils from validated-changeset

* sync lock file
  • Loading branch information
AmauryD authored Oct 22, 2022
1 parent 92e790b commit a04f8e9
Show file tree
Hide file tree
Showing 4 changed files with 2,602 additions and 3,897 deletions.
42 changes: 32 additions & 10 deletions addon/utils/merge-deep.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
import { isChange, getChangeValue, normalizeObject } from 'validated-changeset';
import {
isChange,
getChangeValue,
normalizeObject,
isArrayObject,
objectToArray,
arrayToObject,
} from 'validated-changeset';

function isMergeableObject(value) {
return isNonNullObject(value) && !isSpecial(value);
Expand Down Expand Up @@ -146,17 +153,32 @@ export default function mergeDeep(target, source, options = {}) {
let sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;

if (!sourceAndTargetTypesMatch) {
let sourceIsArrayLike = isArrayObject(source);

if (targetIsArray && sourceIsArrayLike) {
return objectToArray(mergeTargetAndSource(arrayToObject(target), source, options));
}

return source;
} else if (sourceIsArray) {
return source;
}

try {
return mergeTargetAndSource(target, source, options);
} catch (e) {
// this is very unlikely to be hit but lets throw an error otherwise
throw new Error(
'Unable to `mergeDeep` with your data. Are you trying to merge two ember-data objects? Please file an issue with ember-changeset.'
);
} else if (target === null || target === undefined) {
/**
* If the target was set to null or undefined, we always want to return the source.
* There is nothing to merge.
*
* Without this explicit check, typeof null === typeof {any object-like thing}
* which means that mergeTargetAndSource will be called, and you can't merge with null
*/
return source;
} else {
try {
return mergeTargetAndSource(target, source, options);
} catch (e) {
// this is very unlikely to be hit but lets throw an error otherwise
throw new Error(
'Unable to `mergeDeep` with your data. Are you trying to merge two ember-data objects? Please file an issue with ember-changeset.'
);
}
}
}
Loading

0 comments on commit a04f8e9

Please sign in to comment.