73nko
2/20/2020 - 3:09 PM

Interceptors Middleware

const createInterceptorMiddleware = (interceptors) => (store) => (next) => (action) => {
  Promise.all(
    interceptors
      .filter(interceptor => interceptor.type === action.type)
      .map(interceptor => {
        const result = interceptor.handler(action, store.dispatch, store.getState);
        return result instanceof Promise ? result : Promise.resolve(result);
      })
  )
    .then((afterDispatchHandlers) => {
      next(action);
      afterDispatchHandlers.forEach(
        handler => 
          typeof handler === 'function' &&
          handler(action, store.dispatch, store.getState)
      );
    })
    .catch(e => console.error(e));
}

const interceptors = [
  {type: 'INCREMENT', handler: () => doSomeApiStuff()},
  {
    type: 'DECREMENT', 
    handler: () => {
      doOtherApiStuff();  
      return () => doCleanup();
    }
  }
];

const middleware = createInterceptorMiddleware(interceptors);