Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Bower components Debian packages RPM packages NuGet packages

pfchangs / redux-promise   js

Repository URL to install this package:

Version: 0.6.0-alpha 

/ lib / index.js

'use strict';

exports.__esModule = true;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

exports['default'] = promiseMiddleware;

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

var _fluxStandardAction = require('flux-standard-action');

var _lodashUtilityUniqueId = require('lodash/utility/uniqueId');

var _lodashUtilityUniqueId2 = _interopRequireDefault(_lodashUtilityUniqueId);

function isPromise(val) {
  return val && typeof val.then === 'function';
}

function promiseMiddleware(_ref) {
  var dispatch = _ref.dispatch;

  return function (next) {
    return function (action) {
      if (!_fluxStandardAction.isFSA(action)) {
        return isPromise(action) ? action.then(dispatch) : next(action);
      }

      if (isPromise(action.payload)) {
        var _ret = (function () {
          var sequenceId = _lodashUtilityUniqueId2['default']();

          dispatch(_extends({}, action, {
            payload: undefined,
            sequence: {
              type: 'start',
              id: sequenceId
            }
          }));

          return {
            v: action.payload.then(function (result) {
              return dispatch(_extends({}, action, {
                payload: result,
                sequence: {
                  type: 'next',
                  id: sequenceId
                }
              }));
            }, function (error) {
              return dispatch(_extends({}, action, {
                payload: error,
                error: true,
                sequence: {
                  type: 'next',
                  id: sequenceId
                }
              }));
            })['catch'](function (error) {
              console.error(error);
            })
          };
        })();

        if (typeof _ret === 'object') return _ret.v;
      }

      return next(action);
    };
  };
}

module.exports = exports['default'];