All files / json-patch/op OpUndefined.ts

90% Statements 18/20
66.66% Branches 6/9
83.33% Functions 5/6
89.47% Lines 17/19

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  15x   15x 15x             15x   7x               35x 35x 30x 30x   5x           15x       15x       12x 12x       6x 6x 6x      
import type {CompactUndefinedOp, OPCODE_UNDEFINED} from '../codec/compact/types';
import {AbstractPredicateOp} from './AbstractPredicateOp';
import type {OperationUndefined} from '../types';
import {find, type Path, formatJsonPointer} from '@jsonjoy.com/json-pointer';
import {OPCODE} from '../constants';
import type {AbstractOp} from './AbstractOp';
import type {IMessagePackEncoder} from '@jsonjoy.com/json-pack/lib/msgpack';
 
/**
 * @category JSON Predicate
 */
export class OpUndefined extends AbstractPredicateOp<'undefined'> {
  public op() {
    return 'undefined' as const;
  }
 
  public code() {
    return OPCODE.undefined;
  }
 
  public test(doc: unknown) {
    try {
      const {val} = find(doc, this.path);
      const test = val === undefined;
      return test;
    } catch (error) {
      if ((error as Error).message === 'NOT_FOUND') return true;
      throw error;
    }
  }
 
  public toJson(parent?: AbstractOp): OperationUndefined {
    const op: OperationUndefined = {
      op: 'undefined',
      path: formatJsonPointer(parent ? this.path.slice(parent.path.length) : this.path),
    };
    return op;
  }
 
  public toCompact(parent: undefined | AbstractOp, verbose: boolean): CompactUndefinedOp {
    const opcode: OPCODE_UNDEFINED = verbose ? 'undefined' : OPCODE.undefined;
    return [opcode, parent ? this.path.slice(parent.path.length) : this.path];
  }
 
  public encode(encoder: IMessagePackEncoder, parent?: AbstractOp) {
    encoder.encodeArrayHeader(2);
    encoder.writer.u8(OPCODE.undefined);
    encoder.encodeArray(parent ? this.path.slice(parent.path.length) : (this.path as unknown[]));
  }
}