UNPKG

json-joy

Version:

Collection of libraries for building collaborative editing apps.

61 lines (60 loc) 1.87 kB
import { AbstractOp } from './AbstractOp'; import { find, isObjectReference, isArrayReference, formatJsonPointer } from '@jsonjoy.com/json-pointer'; import { OPCODE } from '../constants'; import { clone as deepClone } from '@jsonjoy.com/util/lib/json-clone/clone'; /** * @category JSON Patch */ export class OpReplace extends AbstractOp { value; oldValue; constructor(path, value, oldValue) { super(path); this.value = value; this.oldValue = oldValue; } op() { return 'replace'; } code() { return OPCODE.replace; } apply(doc) { const ref = find(doc, this.path); if (ref.val === undefined) throw new Error('NOT_FOUND'); const value = deepClone(this.value); if (isObjectReference(ref)) ref.obj[ref.key] = value; else if (isArrayReference(ref)) ref.obj[ref.key] = value; else doc = value; return { doc, old: ref.val }; } toJson(parent) { const json = { op: 'replace', path: formatJsonPointer(this.path), value: this.value, }; if (this.oldValue !== undefined) json.oldValue = this.oldValue; return json; } toCompact(parent, verbose) { const opcode = verbose ? 'replace' : 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(OPCODE.replace); encoder.encodeArray(this.path); encoder.encodeAny(this.value); if (hasOldValue) encoder.encodeAny(this.oldValue); } }