"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.promiseMiddleware = void 0;
var tslib_1 = require("tslib");
/**
 * Returns whether the provided value is a promise
 *
 * @hidden
 * @param {object} value Potential promise
 * @return {Boolean}
 */
function isPromise(value) {
    if (value !== null && typeof value === 'object') {
        return value.promise && typeof value.promise.then === 'function';
    }
}
/**
 * @hidden
 */
function promiseMiddleware(_a) {
    var dispatch = _a.dispatch;
    return function (next) { return function (action) {
        if (!isPromise(action.payload)) {
            return next(action);
        }
        var types = action.types, payload = action.payload, meta = action.meta;
        var promise = payload.promise, data = payload.data;
        var PENDING = types[0], FULFILLED = types[1], REJECTED = types[2];
        var p1 = { type: PENDING };
        var p2 = data ? { payload: data } : {};
        var p3 = meta ? { meta: meta } : {};
        /**
         * Dispatch the pending action
         */
        dispatch(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({}, p1), p2), p3));
        /**
         * If successful, dispatch the fulfilled action, otherwise dispatch
         * rejected action.
         */
        return promise.then(function (result) {
            dispatch({
                type: FULFILLED,
                payload: result,
                meta: meta,
            });
        }, function (error) {
            dispatch({
                type: REJECTED,
                payload: error,
                meta: meta,
            });
        });
    }; };
}
exports.promiseMiddleware = promiseMiddleware;
//# sourceMappingURL=promise-middleware.js.map