choerodon-ui
Version:
An enterprise-class UI design language and React-based implementation
80 lines (69 loc) • 2.45 kB
JavaScript
import _regeneratorRuntime from "@babel/runtime/regenerator";
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import Cache from '../_util/Cache';
import { buildURLWithAxiosConfig } from './utils';
export default function throttleAdapterEnhancer(adapter) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var _options$threshold = options.threshold,
threshold = _options$threshold === void 0 ? 1000 : _options$threshold,
_options$cache = options.cache,
cache = _options$cache === void 0 ? new Cache({
max: 10
}) : _options$cache;
var recordCacheWithRequest = function recordCacheWithRequest(index, config) {
var responsePromise = _asyncToGenerator(
/*#__PURE__*/
_regeneratorRuntime.mark(function _callee() {
var response;
return _regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.prev = 0;
_context.next = 3;
return adapter(config);
case 3:
response = _context.sent;
cache.set(index, {
timestamp: Date.now(),
value: Promise.resolve(response)
});
return _context.abrupt("return", response);
case 8:
_context.prev = 8;
_context.t0 = _context["catch"](0);
cache.del(index);
throw _context.t0;
case 12:
case "end":
return _context.stop();
}
}
}, _callee, null, [[0, 8]]);
}))();
cache.set(index, {
timestamp: Date.now(),
value: responsePromise
});
return responsePromise;
};
return function (config) {
var index = buildURLWithAxiosConfig(config);
var now = Date.now();
var cachedRecord = cache.get(index) || {
timestamp: now
};
if (now - cachedRecord.timestamp <= threshold) {
var responsePromise = cachedRecord.value;
if (responsePromise) {
if (process.env.LOGGER_LEVEL === 'info') {
// eslint-disable-next-line no-console
console.info("request cached by throttle adapter: ".concat(index));
}
return responsePromise;
}
}
return recordCacheWithRequest(index, config);
};
}
//# sourceMappingURL=throttleAdapterEnhancer.js.map