diff --git a/src/index.spec.ts b/src/index.spec.ts index 522045f..13fb91b 100644 --- a/src/index.spec.ts +++ b/src/index.spec.ts @@ -653,6 +653,44 @@ describe('a generate json patch function', () => { ]); }); }); + + describe('with maxDepth config', () => { + const before = { + firstLevel: { + secondLevel: { + thirdLevel: { + fourthLevel: 'hello-world', + }, + thirdLevelTwo: 'hello', + }, + }, + }; + + const after = { + firstLevel: { + secondLevel: { + thirdLevel: { + fourthLevel: 'hello-brave-new-world', + }, + thirdLevelTwo: 'hello', + }, + }, + }; + + const patch = generateJSONPatch(before, after, { maxDepth: 3 }); + expect(patch).to.eql([ + { + op: 'replace', + path: '/firstLevel/secondLevel', + value: { + thirdLevel: { + fourthLevel: 'hello-brave-new-world', + }, + thirdLevelTwo: 'hello', + }, + }, + ]); + }); }); function doPatch(json: JsonValue, patch: Patch) { diff --git a/src/index.ts b/src/index.ts index 6bb0b3d..da52d65 100644 --- a/src/index.ts +++ b/src/index.ts @@ -71,6 +71,7 @@ export type JsonPatchConfig = { objectHash?: ObjectHash; propertyFilter?: PropertyFilter; array?: { ignoreMove?: boolean }; + maxDepth?: number; }; export const defaultObjectHash: ObjectHash = (obj, context) => { @@ -82,7 +83,11 @@ export function generateJSONPatch( after: JsonValue, config: JsonPatchConfig = {} ): Patch { - const { objectHash = defaultObjectHash, propertyFilter } = config; + const { + objectHash = defaultObjectHash, + propertyFilter, + maxDepth = Infinity, + } = config; const patch: Patch = []; const hasPropertyFilter = typeof propertyFilter === 'function'; @@ -181,7 +186,11 @@ export function generateJSONPatch( compareArrays(leftValue, rightValue, newPath); } else if (isJsonObject(rightValue)) { if (isJsonObject(leftValue)) { - compareObjects(newPath, leftValue, rightValue); + if (maxDepth <= path.split('/').length) { + patch.push({ op: 'replace', path: path, value: rightJsonValue }); + } else { + compareObjects(newPath, leftValue, rightValue); + } } else if (leftJsonValue.hasOwnProperty(rightKey)) { patch.push({ op: 'replace', path: newPath, value: rightValue }); } else {