UNPKG

json-joy

Version:

Collection of libraries for building collaborative editing apps.

49 lines 1.39 kB
import { AbstractOp } from './AbstractOp'; import { find, isObjectReference, isArrayReference, formatJsonPointer } from '@jsonjoy.com/json-pointer'; import { OPCODE } from '../constants'; /** * @category JSON Patch */ export class OpRemove extends AbstractOp { oldValue; constructor(path, oldValue) { super(path); this.oldValue = oldValue; } op() { return 'remove'; } code() { return OPCODE.remove; } apply(doc) { const ref = find(doc, this.path); if (ref.val === undefined) throw new Error('NOT_FOUND'); if (isObjectReference(ref)) delete ref.obj[ref.key]; else if (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: formatJsonPointer(this.path), }; if (this.oldValue !== undefined) json.oldValue = this.oldValue; return json; } toCompact(parent, verbose) { const opcode = verbose ? 'remove' : OPCODE.remove; return this.oldValue === undefined ? [opcode, this.path] : [opcode, this.path, this.oldValue]; } } //# sourceMappingURL=OpRemove.js.map