All files dispatch.ts

100% Statements 46/46
84.38% Branches 27/32
92.31% Functions 12/13
100% Lines 46/46

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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173              4x 4x   4x         41x 65x       40x     24x 40x 40x   2x     5x     19x   7x                 12x                   140x 100x       10x                             10x                 24x     4x 2x                           6x 3x 3x                                 2x 2x   1x   1x         23x   77x     11x 11x   60x 60x   77x 77x 77x 77x 77x 77x   32x                     11x   66x       2x   2x     40x    
import {
  ISkill,
  IOptions,
  IFlow,
  ICallbacks,
  IIntermediateErrorHandler
} from './types';
import { generateID } from './utils';
import { STATUS, RETURN, START, COMPLETED, NAME } from './constants';
 
export function dispatch(
  callbacks: ICallbacks | undefined,
  skills: ISkill<any>[],
  type: string,
  value: any,
  options: IOptions = {},
  parents: (string | number)[] = [],
  id?: string
) {
  let callback =
    !callbacks || !Array.isArray(callbacks)
      ? callbacks
      : (err?: any, result?: any) =>
          err ? callbacks[0](err) : callbacks[1](result);
  let nextFlows: IFlow<any>[] = [];
  const context = { ...options };
  function setContext(key: string, value: any) {
    context[key] = value;
  }
  function getContext(key: string, defaultValue: any) {
    return context[key] !== undefined ? context[key] : defaultValue;
  }
  if (options.tracker) {
    id = id || generateID();
    if (options[STATUS] === RETURN) {
      options.tracker({
        skill: RETURN,
        type,
        value,
        time: new Date().getTime(),
        id,
        parents
      });
    } else {
      options.tracker({
        skill: START,
        type,
        value,
        time: new Date().getTime(),
        id,
        parents
      });
    }
  }
  function useSkill(value: any, i = 0): any {
    const skill = skills[i];
    function flowReturn(value: any) {
      if (nextFlows.length) {
        // Afterwares present, go for them
        return dispatch(
          callback,
          nextFlows,
          type,
          value,
          {
            ...context,
            [STATUS]: RETURN
          },
          parents,
          id
        );
      } else if (callback) {
        // Finish
        if (options.tracker && id) {
          options.tracker({
            skill: COMPLETED,
            type,
            value,
            time: new Date().getTime(),
            id,
            parents
          });
        }
        return callback(undefined, value);
      }
    }
    function flowReset(type: string, value: any, Econ: any = {}) {
      return dispatch(
        callback,
        skills,
        type,
        value,
        {
          ...options,
          ...con,
          [STATUS]: START
        },
        parents,
        id
      );
    }
    function flowRun<T>(type: string, value: any, Econ: any = {}) {
      return new Promise<T>((yay, nay) => {
        return dispatch(
          [nay, yay],
          skills,
          type,
          value,
          {
            ...options,
            ...con,
            [STATUS]: START
          },
          options.tracker
            ? [...parents, `${id}.${i}${options[STATUS] === RETURN ? '-' : ''}`]
            : []
        );
      });
    }
    function flowCatch(errorHandler: IIntermediateErrorHandler) {
      const originalCallback = callback || ((() => {}) as any);
      callback = function newCallback(err?: any, value?: any) {
        if (err) {
          errorHandler(err, originalCallback);
        } else if (callback) {
          originalCallback(err, value);
        }
      };
    }
    if (!skill) {
      return flowReturn(value);
    }
    const skillName = skill[NAME];
    function flow(newValue: any, nextFlow: any) {
      if (nextFlow) {
        nextFlow[NAME] = skillName;
        nextFlows = [nextFlow, ...nextFlows];
      }
      value = newValue || value;
      return useSkill(value, i + 1);
    }
    flow.reset = flowReset;
    flow.return = flowReturn;
    flow.get = getContext;
    flow.set = setContext;
    flow.run = flowRun;
    flow.catch = flowCatch;
    if (options.tracker) {
      options.tracker({
        skill: skillName,
        type,
        value,
        time: new Date().getTime(),
        id: `${id}.${i}${options[STATUS] === RETURN ? '-' : ''}`,
        parents
      });
    }
    try {
      if (options[STATUS] === RETURN) {
        return (skill as any)(value, flow);
      } else {
        return skill(type, value, flow);
      }
    } catch (err) {
      if (callback) {
        return callback(err);
      }
      throw err;
    }
  }
  return useSkill(value);
}