All files / src/domain/createNotificationsMiddleware index.js

100% Statements 23/23
75% Branches 12/16
100% Functions 5/5
100% Lines 21/21
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                  1x           5x 5x 5x   4x 4x         3x 2x 2x 2x 2x 2x   2x 2x   2x     3x   3x 3x   3x                     2x       2x          
import is from 'is_js';
import invariant from 'invariant';
import createApiActionCreator from 'domain/createApiActionCreator';
import { buildUrl } from 'domain/Api';
import log from 'domain/log';
 
import TimerStrategy from './timer';
import SignalRStrategy from './signalr';
 
const STRATEGIES = {
  timer: TimerStrategy,
  signalr: SignalRStrategy,
};
 
export function createNotificationsMiddleware(config = {}) {
  invariant(is.string(config.strategy), 'trigger strategy must be a string');
  invariant(is.object(config.dispatch), 'trigger dispatch must be an object');
  invariant(is.string(config.dispatch.apiUrl), 'dispatch apiUrl must be a string');
 
  const StrategyClass = STRATEGIES[config.strategy];
  invariant(!! StrategyClass,
      `strategy must be valid (one of ${Object.keys(STRATEGIES).toString()})`);
 
  let emitter;
 
  return (store) => (next) => (action) => {
    const state = store.getState();
    const sso = state && state.get('singleSignOn');
    const user = (sso && sso.get('user')) || {};
    Eif (user && ! is.empty(user)) {
      const accessToken = user.get('access_token');
 
      Eif (is.string(accessToken) && ! emitter) {
        emitter = new StrategyClass(config, accessToken);
 
        emitter.on('notification', () => {
          const {
            method, apiUrl, disableDefault,
          } = config.dispatch;
 
          const fullUrl = buildUrl(apiUrl);
          const actionExtras = disableDefault ? { disableDefault: true } : {};
 
          store.dispatch(
              createApiActionCreator({
                actionObjectName: 'NOTIFICATIONS',
                url: fullUrl,
                method,
                requestExtras: actionExtras,  // disableDefault in request, success, failure
                successExtras: actionExtras,
                failureExtras: actionExtras,
              }));
        });
 
        log.info(`Notification pull strategy: \`${config.strategy}\``);
      }
    }
 
    return next(action);
  };
}
 
export default createNotificationsMiddleware;