All files / json-patch/op OpReplace.ts

96.77% Statements 30/31
100% Branches 13/13
85.71% Functions 6/7
96.15% Lines 25/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63  16x   16x 16x           16x     301x 301x   301x       14x               265x 257x 254x 147x 65x 254x       20x         20x 20x       12x 12x           6x 6x 6x 6x 6x 6x      
import type {CompactReplaceOp, OPCODE_REPLACE} from '../codec/compact/types';
import {AbstractOp} from './AbstractOp';
import type {OperationReplace} from '../types';
import {find, isObjectReference, isArrayReference, type Path, formatJsonPointer} from '@jsonjoy.com/json-pointer';
import {OPCODE} from '../constants';
import type {IMessagePackEncoder} from '@jsonjoy.com/json-pack/lib/msgpack';
 
/**
 * @category JSON Patch
 */
export class OpReplace extends AbstractOp<'replace'> {
  constructor(
    path: Path,
    public readonly value: unknown,
    public readonly oldValue: unknown,
  ) {
    super(path);
  }
 
  public op() {
    return 'replace' as const;
  }
 
  public code() {
    return OPCODE.replace;
  }
 
  public apply(doc: unknown) {
    const ref = find(doc, this.path);
    if (ref.val === undefined) throw new Error('NOT_FOUND');
    if (isObjectReference(ref)) ref.obj[ref.key] = this.value;
    else if (isArrayReference(ref)) ref.obj[ref.key] = this.value;
    else doc = this.value;
    return {doc, old: ref.val};
  }
 
  public toJson(parent?: AbstractOp): OperationReplace {
    const json: OperationReplace = {
      op: 'replace',
      path: formatJsonPointer(this.path),
      value: this.value,
    };
    if (this.oldValue !== undefined) (json as any).oldValue = this.oldValue;
    return json;
  }
 
  public toCompact(parent: undefined | AbstractOp, verbose: boolean): CompactReplaceOp {
    const opcode: OPCODE_REPLACE = verbose ? 'replace' : OPCODE.replace;
    return this.oldValue === undefined
      ? [opcode, this.path, this.value]
      : [opcode, this.path, this.value, this.oldValue];
  }
 
  public encode(encoder: IMessagePackEncoder, parent?: AbstractOp) {
    const hasOldValue = this.oldValue !== undefined;
    encoder.encodeArrayHeader(hasOldValue ? 4 : 3);
    encoder.writer.u8(OPCODE.replace);
    encoder.encodeArray(this.path as unknown[]);
    encoder.encodeAny(this.value);
    if (hasOldValue) encoder.encodeAny(this.oldValue);
  }
}