UNPKG

json-joy

Version:

Collection of libraries for building collaborative editing apps.

46 lines (45 loc) 1.26 kB
import { AbstractOp } from './AbstractOp'; import { find, formatJsonPointer } from '@jsonjoy.com/json-pointer'; import { OpAdd } from './OpAdd'; import { clone as deepClone } from '@jsonjoy.com/util/lib/json-clone/clone'; import { OPCODE } from '../constants'; /** * @category JSON Patch */ export class OpCopy extends AbstractOp { from; constructor(path, from) { super(path); this.from = from; } op() { return 'copy'; } code() { return OPCODE.copy; } apply(doc) { const { val } = find(doc, this.from); if (val === undefined) throw new Error('NOT_FOUND'); const add = new OpAdd(this.path, deepClone(val)).apply(doc); return add; } toJson(parent) { return { op: 'copy', path: formatJsonPointer(this.path), from: formatJsonPointer(this.from), }; } toCompact(parent, verbose) { const opcode = verbose ? 'copy' : OPCODE.copy; return [opcode, this.path, this.from]; } encode(encoder, parent) { encoder.encodeArrayHeader(3); encoder.writer.u8(OPCODE.copy); encoder.encodeArray(this.path); encoder.encodeArray(this.from); } }