UNPKG

tsbase

Version:

Base class libraries for TypeScript

62 lines 2.54 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Cache = void 0; var Query_1 = require("../../Patterns/CommandQuery/Query"); var JsonSerializer_1 = require("../../Utility/Serialization/JsonSerializer"); var Cache = /** @class */ (function () { /** * @param storage the storage interface used to support caching * @param cacheLife EITHER 1.) the amount of milliseconds after the cache is created till it is invalidated | * leaving the default value (0) will result prevent any auto clearing of cache entries * OR 2.) a function defining when the cache is no longer valid; a "false" return will invalidate the cache * @param serializer */ function Cache(storage, cacheLife, serializer) { if (cacheLife === void 0) { cacheLife = 0; } if (serializer === void 0) { serializer = new JsonSerializer_1.JsonSerializer(); } this.storage = storage; this.cacheLife = cacheLife; this.serializer = serializer; } Cache.prototype.Add = function (key, value) { var cacheEntry = { value: value, expiration: typeof this.cacheLife === 'number' && this.cacheLife > 0 ? Date.now() + this.cacheLife : 0 }; this.Delete(key); return this.storage.Set(key, cacheEntry); }; Cache.prototype.Get = function (key, type) { var _this = this; return new Query_1.Query(function () { var result = _this.storage.GetValue(key); var cacheValue = function () { if (_this.cacheIsValid(result)) { return type && typeof result.Value.value === 'object' ? _this.serializer.Deserialize(type, result.Value.value) : result.Value.value; } else { _this.Delete(key); return null; } }; return cacheValue(); }).Execute().Value; }; Cache.prototype.Delete = function (key) { return this.storage.Remove(key); }; Cache.prototype.cacheIsValid = function (result) { if (result.IsSuccess && result.Value) { return typeof this.cacheLife === 'function' ? this.cacheLife(result.Value.value) : (result.Value.expiration === 0 || result.Value.expiration > Date.now()); } return false; }; return Cache; }()); exports.Cache = Cache; //# sourceMappingURL=Cache.js.map