UNPKG

@atlaskit/global-search

Version:

A cross-product search component (batteries included)

83 lines (70 loc) 3.04 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.SimpleCache = void 0; var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); /** * Simple cache that caches exactly one item. */ var SimpleCache = /*#__PURE__*/function () { /** * @param initialValue The initial value, if undefined then the first get() call when initiate the cache value * * @param supplier The callback that will be called if the cache times out or if no existing value exists for the cache. * In the case that the supplier throws an exception the error will not be cached. If there's an error * we will instead return the last known good value but will attempt to refresh the cache again the next time * get() is called. * Any parameters passed into get() will be passed through to supplier. Unlike memoize the cache does not * care about the parameters and will not be invalidated if these parameters change. * * @param timeoutMs The time to wait before allowing the cache to refresh, this defaults to 15 mins. */ function SimpleCache(initialValue, supplier) { var timeoutMs = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : SimpleCache.DEFAULT_TIMEOUT_IN_MS; (0, _classCallCheck2.default)(this, SimpleCache); (0, _defineProperty2.default)(this, "nextCacheRefreshTime", Date.now()); this.timeoutMs = timeoutMs; this.supplier = supplier; if (initialValue) { this.currentValue = initialValue; this.updateNextRefreshTime(); } } (0, _createClass2.default)(SimpleCache, [{ key: "get", value: function get() { if (this.currentValue && Date.now() < this.nextCacheRefreshTime) { return this.currentValue; } this.updateNextRefreshTime(); try { var result = this.supplier.apply(this, arguments); this.currentValue = result; } catch (e) { // If there's an error we will return the last good value but will attempt again on the next get() this.invalidate(); } if (!this.currentValue) { throw new Error('Failed to initialise a value for the cache'); } return this.currentValue; } }, { key: "invalidate", value: function invalidate() { this.nextCacheRefreshTime = Date.now(); } }, { key: "updateNextRefreshTime", value: function updateNextRefreshTime() { this.nextCacheRefreshTime = Date.now() + this.timeoutMs; } }]); return SimpleCache; }(); exports.SimpleCache = SimpleCache; (0, _defineProperty2.default)(SimpleCache, "DEFAULT_TIMEOUT_IN_MS", 15 * 60 * 1000);