UNPKG

tickethead-sdk

Version:

SDK for the Tickethead API

72 lines 3.16 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.attachUpdateProxy = attachUpdateProxy; /** * Wraps the object in a proxy, which allows you to see which updates were made since creation. * This can be useful so only updated fields are sent in patch requests, for example. * Tracks changes done to the first level of the object. To track deep changes, use `attachUpdateProxy`. * Updated fields are present in the `updatedObject` field. * * @param trackedObject an object whose changes will be tracked * @returns proxied object which tracks changes made through it */ function attachShallowUpdateProxy(trackedObject) { const updateTrackingHandler = { get(obj, prop) { // handle accessing the object which contains all the updates if (prop === 'updatedObject') { // We start with the updates on this level of the object const result = Object.assign({}, obj.updated); for (const [key, value] of Object.entries(obj.original)) { if (typeof value === 'object') { const nestedUpdate = value === null || value === void 0 ? void 0 : value.updatedObject; if (nestedUpdate != null) { // and we append the values on the nested objects recursively result[key] = nestedUpdate; } } } return result; } // when accessing something that was updated, return that instead of the original data if (obj.updated[prop] !== undefined) { return obj.updated[prop]; } // The default behavior to return the value return obj.original[prop]; }, set(obj, prop, newValue) { // This way you can reset updates, essentially reverting changes if (prop === 'updatedObject') { obj.updated = newValue; return true; } // The default behavior to store the value obj.updated[prop] = newValue; // Indicate success return true; }, }; return new Proxy({ original: trackedObject, updated: {} }, updateTrackingHandler); } /** * Wraps the object in a proxy, which allows you to see which updates were made since the proxies creation. * This can be useful so only updated fields are sent in patch requests, for example. * Updated fields are present in the `updatedObject` field. * * @param trackedObject an object whose changes will be tracked * @returns proxied object which tracks changes made through it */ function attachUpdateProxy(trackedObject) { if (typeof trackedObject !== 'object') { return trackedObject; } for (const key of Object.keys(trackedObject)) { if (typeof trackedObject[key] === 'object') { ; trackedObject[key] = attachUpdateProxy(trackedObject[key]); } } return attachShallowUpdateProxy(trackedObject); } //# sourceMappingURL=update-proxy.js.map