@ncodedcode/ncode_react_lib
Version:
ncode react application context library
70 lines • 3 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.NCCache = void 0;
var Inject_1 = require("../../di/Inject");
var NCJsonSerializer_1 = require("../../utils/NCJsonSerializer");
var NCStorage_1 = require("./NCStorage");
var DataRecord = (function () {
function DataRecord(data, expiredAt) {
this.data = data;
this.expiredAt = expiredAt;
}
return DataRecord;
}());
var NCCache = (function () {
function NCCache(isInstant) {
if (isInstant === void 0) { isInstant = true; }
this.storage = (0, Inject_1.Inject)(isInstant ? NCStorage_1.NCInstantStorageClassName : NCStorage_1.NCStorageClassName);
}
NCCache.prototype.nowInMilli = function () {
return new Date().getTime();
};
NCCache.prototype.put = function (key, value, expiredAfter) {
if (expiredAfter === void 0) { expiredAfter = NCCache.DEFAULT_EXPIRED_REMAIN; }
var cacheKey = "cache-".concat(key);
var expiredAt = this.nowInMilli() + expiredAfter;
var record = new DataRecord(value, expiredAt);
this.storage.save(cacheKey, NCJsonSerializer_1.NCJsonSerializer.encode(record)).then(function () { });
};
NCCache.prototype.get = function (key) {
var _this = this;
var cacheKey = "cache-".concat(key);
return this.storage.load(cacheKey).then(function (recordJson) {
if (!recordJson)
return null;
var record = NCJsonSerializer_1.NCJsonSerializer.decode(recordJson);
var now = _this.nowInMilli();
if (record.expiredAt <= now) {
_this.storage.delete(cacheKey).then(function () { });
return null;
}
return record.data;
});
};
NCCache.prototype.putNumber = function (key, value, expiredAfter) {
if (expiredAfter === void 0) { expiredAfter = NCCache.DEFAULT_EXPIRED_REMAIN; }
this.put(key, value.toString(), expiredAfter);
};
NCCache.prototype.putObject = function (key, value, expiredAfter) {
if (expiredAfter === void 0) { expiredAfter = NCCache.DEFAULT_EXPIRED_REMAIN; }
this.put(key, NCJsonSerializer_1.NCJsonSerializer.encode(value), expiredAfter);
};
NCCache.prototype.getNumber = function (key, defaultValue) {
if (defaultValue === void 0) { defaultValue = 0; }
return Number(this.get(key) || defaultValue);
};
NCCache.prototype.getObject = function (key) {
return this.get(key).then(function (json) {
if (!json)
return null;
return NCJsonSerializer_1.NCJsonSerializer.decode(json);
});
};
NCCache.EXPIRED_A_MINUTE = 60 * 1000;
NCCache.EXPIRED_A_HOUR = 60 * NCCache.EXPIRED_A_MINUTE;
NCCache.EXPIRED_A_DAY = 24 * NCCache.EXPIRED_A_HOUR;
NCCache.DEFAULT_EXPIRED_REMAIN = 12 * NCCache.EXPIRED_A_HOUR;
return NCCache;
}());
exports.NCCache = NCCache;
//# sourceMappingURL=NCCache.js.map