UNPKG

json-joy

Version:

Collection of libraries for building collaborative editing apps.

63 lines (62 loc) 2.07 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]; } encode(encoder, parent) { const hasOldValue = this.oldValue !== undefined; encoder.encodeArrayHeader(hasOldValue ? 4 : 3); encoder.writer.u8(constants_1.OPCODE.replace); encoder.encodeArray(this.path); encoder.encodeAny(this.value); if (hasOldValue) encoder.encodeAny(this.oldValue); } } exports.OpReplace = OpReplace;