UNPKG

json-joy

Version:

Collection of libraries for building collaborative editing apps.

57 lines (56 loc) 1.66 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]; } encode(encoder, parent) { const hasOldValue = this.oldValue !== undefined; encoder.encodeArrayHeader(hasOldValue ? 3 : 2); encoder.writer.u8(OPCODE.remove); encoder.encodeArray(this.path); if (hasOldValue) encoder.encodeAny(this.oldValue); } }