redux-cached-api-middleware
Version:
API caching solution for redux apps
94 lines (73 loc) • 3.31 kB
JavaScript
var _this = this;
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
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; }
import { RSAA } from 'redux-api-middleware';
import cacheStrategies from './cache';
import config from './config';
import * as types from './actionTypes';
import * as selectors from './selectors';
export var invalidateCache = function invalidateCache(payload) {
return {
type: types.INVALIDATE_CACHE,
payload: payload
};
};
export var clearCache = function clearCache(payload) {
return {
type: types.CLEAR_CACHE,
payload: payload
};
};
var invoke = function invoke(_ref) {
var cache = _ref.cache,
restOptions = _objectWithoutProperties(_ref, ['cache']);
return function () {
var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(dispatch, getState) {
var _dispatch;
var action, cacheStrategy, result;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
action = Object.assign({ types: [] }, config.DEFAULT_INVOKE_OPTIONS, restOptions);
if (!(cache && cache.key)) {
_context.next = 12;
break;
}
cacheStrategy = cache.strategy || config.DEFAULT_CACHE_STRATEGY;
result = selectors.getResult(getState(), cache.key);
action.types = [{ type: types.FETCH_START, meta: { cache: cache } }, { type: types.FETCH_SUCCESS, meta: { cache: cache } }, { type: types.FETCH_ERROR, meta: { cache: cache } }];
if (!cache.shouldFetch) {
_context.next = 10;
break;
}
if (cache.shouldFetch({ state: result })) {
_context.next = 8;
break;
}
return _context.abrupt('return', undefined);
case 8:
_context.next = 12;
break;
case 10:
if (!(cacheStrategy && !cacheStrategies.get(cacheStrategy.type).shouldFetch({ state: result, strategy: cacheStrategy }))) {
_context.next = 12;
break;
}
return _context.abrupt('return', undefined);
case 12:
return _context.abrupt('return', dispatch((_dispatch = {}, _dispatch[RSAA] = action, _dispatch)));
case 13:
case 'end':
return _context.stop();
}
}
}, _callee, _this);
}));
return function (_x, _x2) {
return _ref2.apply(this, arguments);
};
}();
};
export { invoke };
//# sourceMappingURL=actions.js.map