Skip to content
This repository has been archived by the owner on Jun 9, 2019. It is now read-only.

Custom Operator

mohayonao edited this page Oct 15, 2016 · 3 revisions

Description

TODO: write description

Quick Example

define custom operator

const custom = {
  ["@increment"](api, patch) {
    const value = api.get(patch.path);

    // return undefined if patch.path not found
    if (value === undefined) {
      return "ERROR!"; // should return error message if error occur
    }

    return api.replace(patch.path, value + patch.value);
  },
};

apply patches to a next object

const prevObject = { value: 10 };
const patches = [
  { op: "@increment", path: "/value", value: 5 },
];

const nextObject = patch(prevObject, patches, { custom });
// → { value: 15 }

API

syntax

  • (api, patch, index, patches): ?string
    • api: object
      • see below
    • patch: object
      • the current patch being processed in the patches.
    • index: number
      • the index of the current patch being processed in the patches.
    • patches: object[]
      • the array that patch() is being applied to.
    • returns
      • succeeded: not return anything (undefined)
      • failed: return errorMessage: string

operation methods

  • api.add(path: string, value: any): ?string
  • api.remove(path: string): ?string
  • api.replace(path: string, value: any): ?string
  • api.move(from: string, path: string): ?string
  • api.copy(from: string, path: string): ?string
  • api.test(path: string, expected: any): ?string

CAUTION: operation methods basically return undefined (when succeeded). but if error occurs, they return an error message.

if ( ! api.test("/path/to/value", 1) ) {
  // test passing
}

get

  • api.get(path: string): ?any
    • return value in the path. if the path not found, return undefined.

utility methods

  • api.deepEqual(a: any, b: any): boolean
  • api.shallowCopy(a: any): any
  • api.toKeys(path: string): string[]

Examples

@increment

const custom = {
  ["@increment"](api, patch) {
    const value = api.get(patch.path);

    if (value === undefined) {
      return `[op:@increment] path not found: ${ patch.path }`;
    }

    return api.replace(patch.path, value + patch.value);
  },
};

@toggle

const custom = {
  ["@toggle"](api, patch) {
    const value = api.get(patch.path);

    if (value === undefined) {
      return `[op:@toggle] path not found: ${ patch.path }`;
    }

    return api.replace(patch.path, !value);
  },
};

@map

const custom = {
  ["@map"](api, patch) {
    const value = api.get(patch.path);

    if (!Array.isArray(value)) {
      return `[op:@map] value in the path is not array: ${ patch.path }`;
    }

    return api.replace(patch.path, value.map(patch.map));
  },
};