All files / json-patch/op OpInc.ts

95.45% Statements 21/22
100% Branches 4/4
85.71% Functions 6/7
95.23% Lines 20/21

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  15x   15x 15x           15x     98x   98x       16x               78x 78x 78x 10x 78x       10x         10x       8x 8x       4x 4x 4x 4x      
import type {CompactIncOp, OPCODE_INC} from '../codec/compact/types';
import {AbstractOp} from './AbstractOp';
import type {OperationInc} from '../types';
import {find, 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 Extended
 */
export class OpInc extends AbstractOp<'inc'> {
  constructor(
    path: Path,
    public readonly inc: number,
  ) {
    super(path);
  }
 
  public op() {
    return 'inc' as const;
  }
 
  public code() {
    return OPCODE.inc;
  }
 
  public apply(doc: unknown) {
    const ref = find(doc, this.path);
    const result = this.inc + Number(ref.val);
    if (ref.obj) (ref as any).obj[(ref as any).key] = result;
    else doc = result;
    return {doc, old: ref.val};
  }
 
  public toJson(parent?: AbstractOp): OperationInc {
    const op: OperationInc = {
      op: 'inc',
      path: formatJsonPointer(this.path),
      inc: this.inc,
    };
    return op;
  }
 
  public toCompact(parent: undefined | AbstractOp, verbose: boolean): CompactIncOp {
    const opcode: OPCODE_INC = verbose ? 'inc' : OPCODE.inc;
    return [opcode, this.path, this.inc];
  }
 
  public encode(encoder: IMessagePackEncoder, parent?: AbstractOp) {
    encoder.encodeArrayHeader(3);
    encoder.writer.u8(OPCODE.inc);
    encoder.encodeArray(this.path as unknown[]);
    encoder.encodeNumber(this.inc);
  }
}