All files / json-ot/types/ot-json json-patch.ts

96.87% Statements 31/32
83.33% Branches 10/12
100% Functions 2/2
96.66% Lines 29/30

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 633x 3x 3x         3x 268x 268x   13x 13x 13x     28x     21x 21x     186x 186x 186x     11x 11x 11x 11x     9x 9x 9x                           3x 261x 261x 260x   260x   260x     261x    
import {literal} from '@jsonjoy.com/json-expression/lib/util';
import {OpTree} from './tree';
import {toPath} from '@jsonjoy.com/json-pointer/lib/util';
import type {Operation} from '../../../json-patch';
import type {Expr} from '@jsonjoy.com/json-expression';
import type {JsonOp} from './types';
 
export const jsonPatchOpToJsonOp = (operation: Operation): JsonOp => {
  const op = operation.op;
  switch (op) {
    case 'test': {
      const value = literal(operation.value);
      const expression: Expr = [operation.not ? '!=' : '==', ['$', operation.path], value];
      return [[expression]];
    }
    case 'add': {
      return [[], [], [[0, operation.value]], [[0, toPath(operation.path)]]];
    }
    case 'remove': {
      const path = toPath(operation.path);
      return [[['$?', operation.path]], [[0, path]]];
    }
    case 'replace': {
      const path = toPath(operation.path);
      const test: Expr[] = path.length ? [['$?', operation.path]] : [];
      return [test, [[0, path]], [[1, operation.value]], [[1, path]]];
    }
    case 'move': {
      const path = toPath(operation.path);
      const from = toPath(operation.from);
      const test: Expr[] = from.length ? [['$?', operation.from]] : [];
      return [test, [[0, from]], [], [[0, path]]];
    }
    case 'copy': {
      const path = toPath(operation.path);
      const from = toPath(operation.from);
      return [
        [],
        [[0, from]],
        [],
        [
          [0, from],
          [0, path],
        ],
      ];
    }
  }
  return [[]];
};
 
export const toJsonOp = (patch: Operation[]): JsonOp => {
  const tree = OpTree.from([[]]);
  for (const op of patch) {
    const otOp = jsonPatchOpToJsonOp(op);
    // console.log(tree + '');
    const opTree = OpTree.from(otOp);
    // console.log(opTree + '');
    tree.compose(opTree);
    // console.log(tree + '');
  }
  return tree.toJson();
};