UNPKG

json-joy

Version:

Collection of libraries for building collaborative editing apps.

60 lines (59 loc) 1.86 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.OpRemove = void 0; const AbstractOp_1 = require("./AbstractOp"); const json_pointer_1 = require("@jsonjoy.com/json-pointer"); const constants_1 = require("../constants"); /** * @category JSON Patch */ class OpRemove extends AbstractOp_1.AbstractOp { constructor(path, oldValue) { super(path); this.oldValue = oldValue; } op() { return 'remove'; } code() { return constants_1.OPCODE.remove; } apply(doc) { const ref = (0, json_pointer_1.find)(doc, this.path); if (ref.val === undefined) throw new Error('NOT_FOUND'); if ((0, json_pointer_1.isObjectReference)(ref)) delete ref.obj[ref.key]; else if ((0, json_pointer_1.isArrayReference)(ref)) { if (ref.val !== undefined) ref.obj.splice(ref.key, 1); } else doc = null; return { doc, old: ref.val }; } toJson(parent) { const json = { op: 'remove', path: (0, json_pointer_1.formatJsonPointer)(this.path), }; if (this.oldValue !== undefined) json.oldValue = this.oldValue; return json; } toCompact(parent, verbose) { const opcode = verbose ? 'remove' : constants_1.OPCODE.remove; return this.oldValue === undefined ? [opcode, this.path] : [opcode, this.path, this.oldValue]; } encode(encoder, parent) { const hasOldValue = this.oldValue !== undefined; encoder.encodeArrayHeader(hasOldValue ? 3 : 2); encoder.writer.u8(constants_1.OPCODE.remove); encoder.encodeArray(this.path); if (hasOldValue) encoder.encodeAny(this.oldValue); } } exports.OpRemove = OpRemove;