All files / src Epic.ts

69.81% Statements 37/53
83.87% Branches 26/31
81.25% Functions 13/16
69.23% Lines 36/52

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 174 175 176                                                  12x 12x                                 14x                                                 2x                         32x 16x 16x 16x 16x 1x   15x 3x     12x 1x     11x     18x   3x   15x             15x 13x   4x 2x                                                 18x 18x 12x   18x 18x 15x         16x 4x   16x 18x 18x         16x       32x 32x                    
import { Observable, defer, from, of, empty } from 'rxjs';
import {
  AC,
  Deps,
  ExtractPayload,
  ActionLike,
  ActionType,
  Action,
} from './types';
import { getACType, isAction } from './utils';
import { mergeMap, catchError } from 'rxjs/operators';
 
type AllowedAction = ActionLike | ActionLike[] | null;
export type EpicResult =
  | Observable<AllowedAction>
  | Promise<AllowedAction>
  | AllowedAction;
 
export type EpicHandler<TAC extends AC> = (
  payload: ExtractPayload<ReturnType<TAC>>,
  deps: Deps,
  action: ReturnType<TAC> & { type: symbol }
) => EpicResult;
 
export class Epic {
  private handlers: Map<symbol, Map<string, EpicHandler<any>[]>> = new Map();
  private moduleHandlers: Map<symbol, EpicHandler<any>[]> = new Map();
 
  attach(epic: Epic) {
    const subHandlers = epic.handlers;
    for (const symbol of epic.handlers.keys()) {
      for (const type of epic.handlers.get(symbol)!.keys()) {
        this.createKey([symbol, type]);
        this.handlers
          .get(symbol)!
          .get(type)!
          .push(...subHandlers.get(symbol)!.get(type));
      }
    }
    return this;
  }
 
  on<TAC extends AC>(ac: TAC, handler: EpicHandler<TAC>) {
    return this.add(ac, handler);
  }
  onMany<TAC extends AC, TAC2 extends AC>(
    ac: [TAC, TAC2],
    handler: EpicHandler<TAC | TAC2>
  ): this;
  onMany<TAC extends AC, TAC2 extends AC, TAC3 extends AC>(
    ac: [TAC, TAC2, TAC3],
    handler: EpicHandler<TAC | TAC2 | TAC3>
  ): this;
  onMany<TAC extends AC, TAC2 extends AC, TAC3 extends AC, TAC4 extends AC>(
    ac: [TAC, TAC2, TAC3, TAC4],
    handler: EpicHandler<TAC | TAC2 | TAC3 | TAC4>
  ): this;
  onMany<
    TAC extends AC,
    TAC2 extends AC,
    TAC3 extends AC,
    TAC4 extends AC,
    TAC5 extends AC
  >(
    ac: [TAC, TAC2, TAC3, TAC4, TAC5],
    handler: EpicHandler<TAC | TAC2 | TAC3 | TAC4 | TAC5>
  ): this;
  onMany(ac: AC[], handler: EpicHandler<AC>) {
    return this.add(ac, handler);
  }
 
  onModule(moduleSymbol: symbol, handler: EpicHandler<AC>) {
    if (!this.moduleHandlers.has(moduleSymbol)) {
      this.moduleHandlers.set(moduleSymbol, []);
    }
    this.moduleHandlers.get(moduleSymbol!)!.push(handler);
    return this;
  }
 
  // tslint:disable-next-line:no-empty
  toStream(sourceAction: Action, deps: Deps, log: () => void = () => {}) {
    return this.getHandlers(sourceAction).map(handler => {
      return defer(() => {
        log();
        const result = handler(sourceAction.payload, deps, sourceAction);
        if (Array.isArray(result)) {
          return from(result);
        }
        if (isAction(result)) {
          return of(result);
        }
 
        if (result === null) {
          return of(null);
        }
 
        return result;
      }).pipe(
        mergeMap((action: unknown) => {
          if (action === null) {
            // ignore if action is null
            return empty();
          }
          Iif (action === undefined) {
            console.error('Undefined action returned in epic.', {
              action,
              store: name,
            });
            return empty();
          }
          if (isAction(action)) {
            return of(action);
          }
          Eif (Array.isArray(action) && action.every(a => isAction(a))) {
            return action;
          }
          console.error('Invalid action returned in epic.', {
            sourceAction,
            action,
            store: name,
          });
          return empty();
        }),
        catchError(err => {
          console.error(
            'An unhandled error occurred in epic.',
            {
              sourceAction,
              store: name,
            },
            err
          );
          return empty();
        })
      );
    });
  }
 
  private createKey(actionType: ActionType) {
    const [symbol, type] = actionType;
    if (!this.handlers.has(symbol)) {
      this.handlers.set(symbol, new Map());
    }
    const map = this.handlers.get(symbol)!;
    if (!map.has(type)) {
      map.set(type, []);
    }
  }
 
  private add(ac: AC | AC[], handler: EpicHandler<AC>) {
    const keys = Array.isArray(ac)
      ? ac.map(x => getACType(x))
      : [getACType(ac)];
    keys.forEach(([symbol, type]) => {
      this.createKey([symbol, type]);
      this.handlers
        .get(symbol)!
        .get(type)!
        .push(handler);
    });
    return this;
  }
 
  private getHandlers(action: Action) {
    const [symbol, type] = action.type;
    return [
      ...(this.handlers.has(symbol) && this.handlers.get(symbol)!.has(type)
        ? this.handlers.get(symbol)!.get(type)
        : []),
      ...(this.moduleHandlers.has(symbol)
        ? this.moduleHandlers.get(symbol)
        : []),
    ];
  }
}