|
1 | 1 | import * as jsonPatch from 'fast-json-patch';
|
2 |
| -import deepExtend from 'deep-extend'; |
3 |
| -import cloneDeep from 'lodash/cloneDeep'; |
| 2 | +import deepmerge from 'deepmerge'; |
4 | 3 |
|
5 | 4 | export default {
|
6 | 5 | add,
|
@@ -40,42 +39,8 @@ function applyPatch(obj, patch, opts) {
|
40 | 39 | jsonPatch.applyPatch(obj, [replace(patch.path, newValue)]);
|
41 | 40 | } else if (patch.op === 'mergeDeep') {
|
42 | 41 | const currentValue = getInByJsonPath(obj, patch.path);
|
43 |
| - |
44 |
| - // Iterate the properties of the patch |
45 |
| - // eslint-disable-next-line no-restricted-syntax, guard-for-in |
46 |
| - for (const prop in patch.value) { |
47 |
| - const propVal = patch.value[prop]; |
48 |
| - const isArray = Array.isArray(propVal); |
49 |
| - if (isArray) { |
50 |
| - // deepExtend doesn't merge arrays, so we will do it manually |
51 |
| - const existing = currentValue[prop] || []; |
52 |
| - currentValue[prop] = existing.concat(propVal); |
53 |
| - } else if (isObject(propVal) && !isArray) { |
54 |
| - // If it's an object, iterate it's keys and merge |
55 |
| - // if there are conflicting keys, merge deep, otherwise shallow merge |
56 |
| - let currentObj = { ...currentValue[prop] }; |
57 |
| - // eslint-disable-next-line no-restricted-syntax |
58 |
| - for (const key in propVal) { |
59 |
| - if (Object.prototype.hasOwnProperty.call(currentObj, key)) { |
60 |
| - // if there is a single conflicting key, just deepExtend the entire value |
61 |
| - // and break from the loop (since all future keys are also merged) |
62 |
| - // We do this because we can't deepExtend two primitives |
63 |
| - // (currentObj[key] & propVal[key] may be primitives). |
64 |
| - // |
65 |
| - // we also deeply assign here, since we aren't in control of |
66 |
| - // how deepExtend affects existing nested objects |
67 |
| - currentObj = deepExtend(cloneDeep(currentObj), propVal); |
68 |
| - break; |
69 |
| - } else { |
70 |
| - Object.assign(currentObj, { [key]: propVal[key] }); |
71 |
| - } |
72 |
| - } |
73 |
| - currentValue[prop] = currentObj; |
74 |
| - } else { |
75 |
| - // It's a primitive, just replace existing |
76 |
| - currentValue[prop] = propVal; |
77 |
| - } |
78 |
| - } |
| 42 | + const newValue = deepmerge(currentValue, patch.value); |
| 43 | + obj = jsonPatch.applyPatch(obj, [replace(patch.path, newValue)]).newDocument; |
79 | 44 | } else if (patch.op === 'add' && patch.path === '' && isObject(patch.value)) {
|
80 | 45 | // { op: 'add', path: '', value: { a: 1, b: 2 }}
|
81 | 46 | // has no effect: json patch refuses to do anything.
|
|
0 commit comments