All files / json-patch/op OpAdd.ts

96.55% Statements 28/29
100% Branches 10/10
85.71% Functions 6/7
96% Lines 24/25

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  19x   19x 19x 19x           19x     674x   674x       89x               545x 529x 529x 452x   107x 107x 60x 56x   525x       43x               28x 28x       14x 14x 14x 14x      
import type {CompactAddOp, OPCODE_ADD} from '../codec/compact/types';
import {AbstractOp} from './AbstractOp';
import type {OperationAdd} from '../types';
import {find, type Path, formatJsonPointer} from '@jsonjoy.com/json-pointer';
import {OPCODE} from '../constants';
import {clone as deepClone} from '@jsonjoy.com/util/lib/json-clone/clone';
import type {IMessagePackEncoder} from '@jsonjoy.com/json-pack/lib/msgpack';
 
/**
 * @category JSON Patch
 */
export class OpAdd extends AbstractOp<'add'> {
  constructor(
    path: Path,
    public readonly value: unknown,
  ) {
    super(path);
  }
 
  public op() {
    return 'add' as const;
  }
 
  public code() {
    return OPCODE.add;
  }
 
  public apply(doc: unknown) {
    const {val, key, obj} = find(doc, this.path) as any;
    const value = deepClone(this.value);
    if (!obj) doc = value;
    else if (typeof key === 'string') obj[key] = value;
    else {
      const length = obj.length;
      if (key < length) obj.splice(key, 0, value);
      else if (key > length) throw new Error('INVALID_INDEX');
      else obj.push(value);
    }
    return {doc, old: val};
  }
 
  public toJson(parent?: AbstractOp): OperationAdd {
    return {
      op: 'add',
      path: formatJsonPointer(this.path),
      value: this.value,
    };
  }
 
  public toCompact(parent: undefined | AbstractOp, verbose: boolean): CompactAddOp {
    const opcode: OPCODE_ADD = verbose ? 'add' : OPCODE.add;
    return [opcode, this.path, this.value];
  }
 
  public encode(encoder: IMessagePackEncoder) {
    encoder.encodeArrayHeader(3);
    encoder.writer.u8(OPCODE.add);
    encoder.encodeArray(this.path as unknown[]);
    encoder.encodeAny(this.value);
  }
}