Starcounter-Jack / JSON-Patch

Lean and mean Javascript implementation of the JSON-Patch standard (RFC 6902). Update JSON documents using delta patches.
MIT License
1.82k stars 215 forks source link

Add option to relax applyPatch to add if path does not exist? #199

Closed villesau closed 6 years ago

villesau commented 6 years ago

I have a case where I'd like to get only changed values as a new object. This is useful for many APIs which are able to take also subset of values, updating just delivered values and leaving the rest alone. This could be achieved like this:

jsonPatch.applyPatch({}, jsonPatch.compare({val: 123, val2: 123}, {val: 321, val2: 123})).newValue; // {val: 321}

But in case of nested objects things gets difficult:

jsonPatch.applyPatch({}, jsonPatch.compare({nested: {value: 321}}, {nested: {value: 123}}))

Here applyPatch throws as it can't replace the value since key nested is not found. I tried to go around this by mapping over compare result and forcing the op to add. This didn't work well either.

I thing good solution for this would be to have flag to relax the applyPatch to behave like 'add if not found'. Even easier for the library user would be to have diffDocument object returned by compare, in similar way than applyPatch returns newDocument. Would this make sense in context of this lib?

warpech commented 6 years ago

Thanks for suggesting, but sorry, this is directly against the spec.

See the last paragraph of the section 4.1 in the spec: https://tools.ietf.org/html/rfc6902#section-4.1

There is a test for that in https://github.com/json-patch/json-patch-tests/blob/86ad182cbc2ba0c4ed0f539753a283c6c9755f21/spec_tests.json#L7

You will have to solve it differently.

Closing as won't fix.