UNPKG

redux-taxi

Version:

Inform server-side rendering from the component level when dealing with asynchronous actions.

83 lines (67 loc) 2.81 kB
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.DONE = exports.START = undefined; var _promise = require('babel-runtime/core-js/promise'); var _promise2 = _interopRequireDefault(_promise); var _extends2 = require('babel-runtime/helpers/extends'); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = require('babel-runtime/helpers/objectWithoutProperties'); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); exports.default = PromiseMiddleware; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * PromiseMiddleware * * Lets you dispatch special actions with a { promise } field. * * This middleware will turn them into a single action at the beginning, * and a single success (or failure) action when the `promise` resolves. * It also generates a unique ID for the special meta sequence object * that it attaches to the action, see issue#7 in flux-standard-action, * https://github.com/acdlite/flux-standard-action/issues/7 * * For convenience, `dispatch` will return the promise so the caller can wait. * */ var START = exports.START = 'START'; var DONE = exports.DONE = 'DONE'; function generateRandomId() { return Math.random().toString(36).slice(-5); } function sequence(id, type) { return { sequence: { id: id, type: type } }; } function PromiseMiddleware() { return function (next) { return function (action) { var promise = action.promise, rest = (0, _objectWithoutProperties3.default)(action, ['promise']); var id = generateRandomId(); if (!promise) { return next(action); } next((0, _extends3.default)({}, rest, sequence(id, START))); return promise.then(function (payload) { return next((0, _extends3.default)({}, rest, { payload: payload }, sequence(id, DONE))); }, function (reason) { var error = reason; // By FSA definition, payload SHOULD be an error object // Promises in turn don't require reason to be an Error if (!(error instanceof Error)) { var message = reason; if (typeof message !== 'string') { message = 'Promise rejected with data. See error.data field.'; } error = new Error(message); error.data = reason; } next((0, _extends3.default)({}, rest, { payload: error, error: true }, sequence(id))); return _promise2.default.reject(reason); // Don't break the promise chain }); }; }; }