@bitblit/ratchet-common
Version:
Common tools for general use
73 lines • 2.7 kB
JavaScript
import { Logger } from '../logger/logger.js';
import { ErrorRatchet } from './error-ratchet.js';
import { LoggerLevelName } from '../logger/logger-level-name.js';
export class ExpiringObject {
_config;
_cacheObject;
_lastUpdatedEpochMS;
_timeRemainingMS;
constructor(inputConfig) {
this._config = Object.assign({}, this.defaultConfig(), inputConfig || {});
if (this._config.overrideTimeRemainingMS && this._config.timeToLiveMS) {
ErrorRatchet.throwFormattedErr('Cannot define both time to live and overrideTimeRemainingMS');
}
if (!this._config.overrideTimeRemainingMS && !this._config.timeToLiveMS) {
ErrorRatchet.throwFormattedErr('Must define exactly one of timeToLiveMS or overrideTimeRemainingMS');
}
if (this._config.initialValue) {
this.update(this._config.initialValue);
}
this._timeRemainingMS = this._config.overrideTimeRemainingMS || this.defaultTimeRemainingMS;
}
defaultConfig() {
const rval = {
generator: null,
initialValue: null,
logLevel: LoggerLevelName.debug,
overrideTimeRemainingMS: null,
timeToLiveMS: 1_000 * 60,
};
return rval;
}
async defaultTimeRemainingMS(lastUpdatedEpochMS) {
let rval = 0;
if (lastUpdatedEpochMS) {
const ageMS = new Date().getTime() - lastUpdatedEpochMS;
rval = Math.max(0, this._config.timeToLiveMS - ageMS);
}
return rval;
}
update(newValue, doNotUpdateClock = false) {
this._cacheObject = newValue;
if (!doNotUpdateClock) {
this._lastUpdatedEpochMS = new Date().getTime();
}
Logger.logByLevel(this._config.logLevel, 'Updated cache value to %j', newValue);
}
async fetchCacheObjectTimeRemainingMS() {
return this._timeRemainingMS(this._lastUpdatedEpochMS);
}
async fetch() {
const remainMS = await this._timeRemainingMS(this._lastUpdatedEpochMS);
if (!remainMS) {
this._cacheObject = null;
this._lastUpdatedEpochMS = null;
}
if (!this._cacheObject) {
if (this._config.generator) {
const newValue = await this._config.generator();
Logger.logByLevel(this._config.logLevel, 'Auto call to generator returned %j', newValue);
this.update(newValue);
}
}
return this._cacheObject;
}
}
export class ExpiringObjectConfig {
timeToLiveMS;
generator;
initialValue;
logLevel;
overrideTimeRemainingMS;
}
//# sourceMappingURL=expiring-object.js.map