'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 = requestMiddleware;

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

function requestMiddleware(request) {
  return function (_ref) {
    var dispatch = _ref.dispatch,
        getState = _ref.getState;

    return function (next) {
      return function (action) {
        if (typeof action === 'function') {
          return action(dispatch, getState);
        }

        var promise = action.promise,
            types = action.types,
            rest = _objectWithoutProperties(action, ['promise', 'types']); // eslint-disable-line no-redeclare


        if (!promise) {
          return next(action);
        }

        var REQUEST = types[0],
            SUCCESS = types[1],
            FAILURE = types[2];

        next(_extends({}, rest, { type: REQUEST }));

        var actionPromise = promise(request);
        actionPromise.then(function (result) {
          return next(_extends({}, rest, { result: result, type: SUCCESS }));
        }, function (error) {
          return next(_extends({}, rest, { error: error, type: FAILURE }));
        }).catch(function (error) {
          console.error('MIDDLEWARE ERROR:', error);
          next(_extends({}, rest, { error: error, type: FAILURE }));
        });

        return actionPromise;
      };
    };
  };
}
module.exports = exports['default'];