All files / json-patch/op OpTestType.ts

96.29% Statements 26/27
80% Branches 12/15
85.71% Functions 6/7
95.65% Lines 22/23

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  15x   15x 15x       15x         15x     102x   102x       18x               72x 72x 64x 52x 20x 16x       15x         15x       12x 12x       6x 6x 6x 6x      
import type {CompactTestTypeOp, OPCODE_TEST_TYPE} from '../codec/compact/types';
import {AbstractPredicateOp} from './AbstractPredicateOp';
import type {OperationTestType, JsTypes, JsonPatchTypes} 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';
 
const {isArray} = Array;
 
/**
 * @category JSON Predicate
 */
export class OpTestType extends AbstractPredicateOp<'test_type'> {
  constructor(
    path: Path,
    public readonly type: JsonPatchTypes[],
  ) {
    super(path);
  }
 
  public op() {
    return 'test_type' as const;
  }
 
  public code() {
    return OPCODE.test_type;
  }
 
  public test(doc: unknown): boolean {
    const {val} = find(doc, this.path);
    if (val === null) return this.type.indexOf('null') > -1;
    if (isArray(val)) return this.type.indexOf('array') > -1;
    if (this.type.indexOf(typeof val as JsTypes) > -1) return true;
    if (typeof val === 'number' && val === Math.round(val) && this.type.indexOf('integer') > -1) return true;
    return false;
  }
 
  public toJson(parent?: AbstractOp): OperationTestType {
    const op: OperationTestType = {
      op: 'test_type',
      path: formatJsonPointer(parent ? this.path.slice(parent.path.length) : this.path),
      type: this.type,
    };
    return op;
  }
 
  public toCompact(parent: undefined | AbstractOp, verbose: boolean): CompactTestTypeOp {
    const opcode: OPCODE_TEST_TYPE = verbose ? 'test_type' : OPCODE.test_type;
    return [opcode, parent ? this.path.slice(parent.path.length) : this.path, this.type];
  }
 
  public encode(encoder: IMessagePackEncoder, parent?: AbstractOp) {
    encoder.encodeArrayHeader(3);
    encoder.writer.u8(OPCODE.test_type);
    encoder.encodeArray(parent ? this.path.slice(parent.path.length) : (this.path as unknown[]));
    encoder.encodeArray(this.type);
  }
}