json-joy
Version:
Collection of libraries for building collaborative editing apps.
52 lines • 1.57 kB
JavaScript
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];
}
}
//# sourceMappingURL=OpReplace.js.map