UNPKG

json-joy

Version:

Collection of libraries for building collaborative editing apps.

54 lines 1.75 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.OpReplace = void 0; const AbstractOp_1 = require("./AbstractOp"); const json_pointer_1 = require("@jsonjoy.com/json-pointer"); const constants_1 = require("../constants"); const clone_1 = require("@jsonjoy.com/util/lib/json-clone/clone"); /** * @category JSON Patch */ class OpReplace extends AbstractOp_1.AbstractOp { constructor(path, value, oldValue) { super(path); this.value = value; this.oldValue = oldValue; } op() { return 'replace'; } code() { return constants_1.OPCODE.replace; } apply(doc) { const ref = (0, json_pointer_1.find)(doc, this.path); if (ref.val === undefined) throw new Error('NOT_FOUND'); const value = (0, clone_1.clone)(this.value); if ((0, json_pointer_1.isObjectReference)(ref)) ref.obj[ref.key] = value; else if ((0, json_pointer_1.isArrayReference)(ref)) ref.obj[ref.key] = value; else doc = value; return { doc, old: ref.val }; } toJson(parent) { const json = { op: 'replace', path: (0, json_pointer_1.formatJsonPointer)(this.path), value: this.value, }; if (this.oldValue !== undefined) json.oldValue = this.oldValue; return json; } toCompact(parent, verbose) { const opcode = verbose ? 'replace' : constants_1.OPCODE.replace; return this.oldValue === undefined ? [opcode, this.path, this.value] : [opcode, this.path, this.value, this.oldValue]; } } exports.OpReplace = OpReplace; //# sourceMappingURL=OpReplace.js.map