All files / packages/tao/src AppCtxHandlers.js

100% Statements 79/79
100% Branches 36/36
100% Functions 27/27
100% Lines 77/77
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 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203        6x 40x 205x         334x   334x 334x 334x 225x       59x 58x   61x 57x   82x         58x 36x 36x   40x 47x         26x 25x   43x 85x           67x 66x   130x 75x 21x         22x 13x 63x         62x 61x   120x 66x 17x         22x 13x 131x         130x 129x   256x 134x 99x         186x 105x 102x               171x       168x       167x       104x             95x   33x 32x 23x   10x 17x 79x   20x           28x                         90x 38x 23x     37x   20x 75x   75x             19x                           142x 89x 75x 75x 19x     71x 18x 18x 18x   1x            
import AppCtxRoot from './AppCtxRoot';
import AppCtx from './AppCtx';
import { isIterable } from './utils';
 
const console = {
  error: () => 1,
  log: () => 1
};
 
export default class AppCtxHandlers extends AppCtxRoot {
  constructor(term, action, orient, leafAppConHandlers) {
    super(term, action, orient);
 
    this._leafAppConHandlers = new Set(leafAppConHandlers);
    this._intercept = new Set();
    this._async = new Set();
    this._inline = new Set();
  }
 
  addLeafHandler(leafAch) {
    if (!(leafAch instanceof AppCtxHandlers)) {
      throw new Error("'leafAch' is not an instance of AppCtxHandlers");
    }
    if (!this.isWildcard || !leafAch.isConcrete) {
      return;
    }
    if (
      (this.isTermWild || this.t === leafAch.t) &&
      (this.isActionWild || this.a === leafAch.a) &&
      (this.isOrientWild || this.o === leafAch.o)
    ) {
      this._leafAppConHandlers.add(leafAch);
      this._intercept.forEach(inHandler =>
        leafAch.addInterceptHandler(inHandler)
      );
      this._async.forEach(aHandler => leafAch.addAsyncHandler(aHandler));
      this._inline.forEach(inHandler => leafAch.addInlineHandler(inHandler));
    }
  }
 
  addLeafHandlers(leafAches) {
    if (!isIterable(leafAches)) {
      this.addLeafHandler(leafAches);
    } else {
      for (let leaf of leafAches) {
        this.addLeafHandler(leaf);
      }
    }
  }
 
  addInterceptHandler(handler) {
    if (typeof handler !== 'function') {
      throw new Error('An InterceptHandler can only be a function');
    }
    this._intercept.add(handler);
    this._leafAppConHandlers.forEach(leafAch =>
      leafAch.addInterceptHandler(handler)
    );
  }
 
  removeInterceptHandler(handler) {
    this._intercept.delete(handler);
    this._leafAppConHandlers.forEach(leafAch =>
      leafAch.removeInterceptHandler(handler)
    );
  }
 
  addAsyncHandler(handler) {
    if (typeof handler !== 'function') {
      throw new Error('An AsyncHandler can only be a function');
    }
    this._async.add(handler);
    this._leafAppConHandlers.forEach(leafAch =>
      leafAch.addAsyncHandler(handler)
    );
  }
 
  removeAsyncHandler(handler) {
    this._async.delete(handler);
    this._leafAppConHandlers.forEach(leafAch =>
      leafAch.removeAsyncHandler(handler)
    );
  }
 
  addInlineHandler(handler) {
    if (typeof handler !== 'function') {
      throw new Error('An InlineHandler can only be a function');
    }
    this._inline.add(handler);
    this._leafAppConHandlers.forEach(leafAch =>
      leafAch.addInlineHandler(handler)
    );
  }
 
  removeInlineHandler(handler) {
    this._inline.delete(handler);
    this._leafAppConHandlers.forEach(leafAch =>
      leafAch.removeInlineHandler(handler)
    );
  }
 
  // Might need but removing to have accurate code coverage metric
  // populateHandlersFromWildcards() {}
 
  get interceptHandlers() {
    return this._intercept.values();
  }
 
  get asyncHandlers() {
    return this._async.values();
  }
 
  get inlineHandlers() {
    return this._inline.values();
  }
 
  async handleAppCon(ac, setAppCtx, control) {
    const { t, a, o, data } = ac;
    /*
     * Intercept Handlers
     * always occur first
     * have the ability to prevent other handlers from firing on this AC
     * optionally can return a single AC that will be set as the new AC instead of the incoming AC
     */
    for (let interceptH of this.interceptHandlers) {
      // using the decorator pattern to call these?
      let intercepted = await interceptH({ t, a, o }, data);
      if (!intercepted) {
        continue;
      }
      if (intercepted instanceof AppCtx) {
        try {
          setAppCtx(intercepted, control);
        } catch (interceptErr) {
          console.log(
            'error setting context returned from intercept handler:',
            interceptErr
          );
        }
      }
      return;
    }
    /*
     * Async Handlers
     * designed to kick off asynchronous handling of an AC outside of the current
     * control loop
     * fire if all Intercept Handlers don't intercept the fired AC
     * work inside of their own execution context
     * can return an AC that will be set as a context inside the async exec ctx
     * TODO: look into how redux-sagas is implemented and may be a way to use
     * generators instead of Promises
     * TODO: would ServiceWorkers make sense for this? tao-sw package
     */
    for (let asyncH of this.asyncHandlers) {
      (() => {
        console.log(
          `>>>>>>>> starting async context within ['${t}', '${a}', '${o}'] <<<<<<<<<<`
        );
        Promise.resolve(asyncH({ t, a, o }, data))
          .then(nextAc => {
            if (nextAc && nextAc instanceof AppCtx) {
              setAppCtx(nextAc, control);
            }
            console.log(
              `>>>>>>>> ending async context within ['${t}', '${a}', '${o}'] <<<<<<<<<<`
            );
          })
          .catch(asyncErr => {
            // swallow async errors
            // possibility to set an AC for errors
            console.error('error in async handler:', asyncErr);
          });
      })();
    }
    /*
     * Inline Handlers
     * fire if all Intercept Handlers don't intercept the fired AC
     * fired after all Async handlers are fired off
     * work inside the same execution context as the caller
     * can return an AC that will be set immediately in the TAO
     * TODO: should these returns be spooled up then iterated to allow
     * all handlers to handle this context before any new ones are set?
     * YES: currently implemented that way
     */
    const nextSpool = [];
    for (let inlineH of this.inlineHandlers) {
      let nextInlineAc = await inlineH({ t, a, o }, data);
      if (nextInlineAc && nextInlineAc instanceof AppCtx) {
        nextSpool.push(nextInlineAc);
      }
    }
    if (nextSpool.length) {
      for (let nextAc of nextSpool) {
        try {
          setAppCtx(nextAc, control);
        } catch (inlineErr) {
          console.error('error on next inline:', inlineErr);
        }
      }
    }
  }
}