tsbase
Version:
Base class libraries for TypeScript
58 lines • 2.24 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Cache = void 0;
const Query_1 = require("../../Patterns/CommandQuery/Query");
const JsonSerializer_1 = require("../../Utility/Serialization/JsonSerializer");
class Cache {
/**
* @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
*/
constructor(storage, cacheLife = 0, serializer = new JsonSerializer_1.JsonSerializer()) {
this.storage = storage;
this.cacheLife = cacheLife;
this.serializer = serializer;
}
Add(key, value) {
const 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);
}
Get(key, type) {
return new Query_1.Query(() => {
const result = this.storage.GetValue(key);
const cacheValue = () => {
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;
}
Delete(key) {
return this.storage.Remove(key);
}
cacheIsValid(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;
}
}
exports.Cache = Cache;
//# sourceMappingURL=Cache.js.map