JSON Merge Patch for a versioned notification policy
A tested shift policy example demonstrates RFC 7396 object merging, member deletion, and complete array replacement.
Archive retrospective · Topic year 2014
In this article
Map the clear command explicitly
Two browser saves expose the difference. Changing only the channel leaves snooze out of the request. Selecting the control that clears an explicit delay sends that member as null under routing. Inspect the response and then reopen the editor. The first save should retain the custom delay, while the second should show the inherited delay. The presence of a numeric value in the interface does not necessarily mean the server stores an explicit override.
Three changes in an alert policy
Imagine a shift team with a routing name, a snooze interval, and two notification channels. An operator wants to change the team, clear its custom delay, and switch to a single push channel. Sending back a complete document copied when the editor opened can accidentally discard an unrelated setting. Three separate field requests would split one intention into independently failing operations. RFC 7396, published in 2014, puts a JSON change document beside the current JSON representation. The example addresses only routing and channels. The active flag, absent from the request, survives. The editor needs the same distinction. It can omit fields the user never touched and send a deletion only when the operator deliberately clears an allowed setting. That separation makes it possible to test the request alongside the form.
Object members and whole values follow different rules
When the patch is an object, the processor visits its named members. A nested object is handled at its own level. A null member tells the processor to remove that key from the resulting object. Deletion of a key that was already absent leaves the object as it was. An array, scalar, or boolean supplied for an ordinary member replaces its previous value completely. In this trial the new push array takes the place of both mail and sms. It never appends a channel implicitly. A root patch that is not an object replaces the whole target. A null root therefore produces a null document, while a null field removes its member. Whether that null document is acceptable depends on the application's schema, which is checked after transformation.
import assert from 'node:assert/strict';
const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
function mergePatch(target, patch) {
if (!isObject(patch)) return structuredClone(patch);
const next = Object.assign(Object.create(null), isObject(target) ? structuredClone(target) : {});
for (const [key, value] of Object.entries(patch)) {
if (value === null) delete next[key];
else Object.defineProperty(next, key, {
value: mergePatch(Object.hasOwn(next, key) ? next[key] : undefined, value),
enumerable: true, writable: true, configurable: true,
});
}
return next;
}
const initial = { routing: { team: 'desk', snooze: 15 }, channels: ['mail', 'sms'], active: true };
const patch = { routing: { snooze: null, team: 'night' }, channels: ['push'] };
const result = mergePatch(initial, patch);
const asJson = value => JSON.parse(JSON.stringify(value));
assert.deepEqual(asJson(result), { routing: { team: 'night' }, channels: ['push'], active: true });
assert.deepEqual(initial.routing, { team: 'desk', snooze: 15 });
assert.deepEqual(asJson(mergePatch(7, { routing: { team: 'desk' } })), { routing: { team: 'desk' } });
assert.equal(mergePatch(initial, null), null);
assert.deepEqual(mergePatch(initial, [42]), [42]);
assert.deepEqual(asJson(mergePatch(result, patch)), asJson(result));
console.log(JSON.stringify({ runtime: process.version, result, checks: 6 }, null, 2));
Six checks with a local JavaScript example
The attached program applies the notification change in memory. The resulting routing object contains team night and loses its snooze field. A single push channel remains and active is still true. The six assertions also check original input integrity, an object patch applied over a non-object target, root null, replacement by a root array, and repeat application to the resulting value. The actual run uses a current Node runtime on Windows. It exercises document transformation without relying on an HTTP framework, a running database, a historical implementation, or a live account. That makes the change and expected value easy to inspect. Request headers, transactional preconditions, and application side effects need their own integration checks because the local fixture has no such operations.
Absence can be different from an explicit unknown
A missing snooze key may activate an inherited default. In another data model, a partner identifier stored as null could mean that the identity is unknown. An object merge patch reserves member-level null for removal, so one operation cannot express both storing that explicit null and deleting the field. A schema that needs three states can give the state a separate field, or an API can use named operations. Arrays raise a different concern. A person replacing one channel by sending a complete array can inadvertently drop another newly added channel if the old document was kept open. The editor should show the resulting complete list and handle any conflicting version. It should not depend on the array to communicate an implicit insertion.
Check the version before accepting the result
Two operators can begin with the same valid document. If one saves first, a second full array replacement may be based on a version that is already obsolete. An HTTP endpoint can expose a strong entity tag and accept a corresponding If-Match condition. When it fails, a 412 response gives the client a reason to reload before reassessing the original change. Check permissions and permitted field names, apply the transform, and validate the resulting full document. Make the final write conditional on the same version that was read so a change between checking and writing cannot silently slip through. Reapplying the same structural patch can yield the same JSON value. Any email, billing event, or audit delivery that accompanies an accepted request still requires its own delivery semantics.
Choose a contract that fits the editing model
Small object-heavy preference documents often fit merge patch well. A reviewer can see which branches change without comparing two complete settings files. A workload dominated by frequent edits to individual elements of large arrays places a different burden on the client, as does a schema that needs explicit null members. Before committing to the contract, test an untouched field, a removed field, a replaced array, an outdated target, and a forbidden change. Keep the reason for a rejected precondition visible to the operator. An audit event can record authorized field names, operation type, and the applied version without capturing every customer value. This gives the save button, server implementation, and operational history a common model of the requested change.
Reader discussion
How would you measure this development's real-world impact?
No comments yet. Be the first to contribute.
Write a comment