All files / packages/tao-utils/src seive.js

5.88% Statements 1/17
0% Branches 0/14
0% Functions 0/5
5.88% Lines 1/17
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      2x                                                                                    
import { Network } from '@tao.js/core';
import trigramFilter from './trigram-filter';
 
const NOOP = () => {};
 
function addControl(name, control) {
  return { ...control, seive: name };
}
 
// filter function signature: (ac:AppCtx, control:Object)
// filters is: [filterFunc, [exact,]] ...trigrams
 
export default function seive(name, source, destination, ...filters) {
  if (
    !source ||
    !(source._network instanceof Network) ||
    !destination ||
    !(destination._network instanceof Network)
  ) {
    return NOOP;
  }
  let filterFunction =
    typeof filters[0] === 'function' ? filters.shift() : undefined;
  let handleFilter = trigramFilter(...filters);
 
  let middleware = (handler, ac, forwardAppCtx, control) => {
    if (filterFunction && !filterFunction(ac, control)) {
      return;
    }
    if (handleFilter(ac)) {
      destination._channel.setAppCtxControl(
        ac,
        addControl(name, control),
        forwardAppCtx
      );
    }
  };
  source._network.use(middleware);
  return () => {
    source._network.stop(middleware);
    middleware = null;
    filterFunction = null;
    handleFilter = null;
  };
}