@bitblit/ratchet-aws
Version:
Common tools for use with AWS browser and node
72 lines • 2.82 kB
JavaScript
import { RequireRatchet } from '@bitblit/ratchet-common/lang/require-ratchet';
import { Logger } from '@bitblit/ratchet-common/logger/logger';
export class RuntimeParameterRatchet {
provider;
cache = new Map();
constructor(provider) {
this.provider = provider;
RequireRatchet.notNullOrUndefined(this.provider);
}
async fetchParameter(groupId, paramKey, defaultValue = null, forceFreshRead = false) {
Logger.debug('Reading parameter %s / %s / Force : %s', groupId, paramKey, forceFreshRead);
const cached = this.cache.get(RuntimeParameterRatchet.toCacheStoreKey(groupId, paramKey));
let rval = null;
const now = new Date().getTime();
if (!forceFreshRead && !!cached) {
const oldest = cached.ttlSeconds ? now - cached.ttlSeconds * 1000 : 0;
if (cached.storedEpochMS > oldest) {
Logger.silly('Fetched %s / %s from cache', groupId, paramKey);
rval = JSON.parse(cached.paramValue);
}
}
if (!rval) {
const temp = await this.readUnderlyingEntry(groupId, paramKey);
if (temp) {
this.addToCache(temp);
rval = JSON.parse(temp.paramValue);
}
}
rval = rval || defaultValue;
return rval;
}
async fetchAllParametersForGroup(groupId) {
const all = await this.readUnderlyingEntries(groupId);
const rval = new Map();
all.forEach((t) => {
rval.set(t.paramKey, JSON.parse(t.paramValue));
this.addToCache(t);
});
return rval;
}
async readUnderlyingEntry(groupId, paramKey) {
return this.provider.readParameter(groupId, paramKey);
}
async readUnderlyingEntries(groupId) {
return this.provider.readAllParametersForGroup(groupId);
}
async storeParameter(groupId, paramKey, paramValue, ttlSeconds) {
const toStore = {
groupId: groupId,
paramKey: paramKey,
paramValue: JSON.stringify(paramValue),
ttlSeconds: ttlSeconds,
};
const _wrote = await this.provider.writeParameter(toStore);
return this.provider.readParameter(groupId, paramKey);
}
static toCacheStoreKey(groupId, paramKey) {
return groupId + ':::' + paramKey;
}
addToCache(temp) {
if (temp) {
const now = new Date().getTime();
const toStore = Object.assign({ storedEpochMS: now }, temp);
this.cache.set(RuntimeParameterRatchet.toCacheStoreKey(temp.groupId, temp.paramKey), toStore);
}
}
clearCache() {
Logger.debug('Clearing runtime parameter cache');
this.cache = new Map();
}
}
//# sourceMappingURL=runtime-parameter-ratchet.js.map