@bitblit/ratchet-aws
Version:
Common tools for use with AWS browser and node
67 lines • 2.64 kB
JavaScript
import { RequireRatchet } from '@bitblit/ratchet-common/lang/require-ratchet';
import { Logger } from '@bitblit/ratchet-common/logger/logger';
import { ErrorRatchet } from '@bitblit/ratchet-common/lang/error-ratchet';
import { PromiseRatchet } from '@bitblit/ratchet-common/lang/promise-ratchet';
export class EnvironmentService {
provider;
cfg;
readPromiseCache = new Map();
static defaultEnvironmentServiceConfig() {
const rval = {
maxRetries: 3,
backoffMultiplierMS: 500,
};
return rval;
}
constructor(provider, cfg = EnvironmentService.defaultEnvironmentServiceConfig()) {
this.provider = provider;
this.cfg = cfg;
RequireRatchet.notNullOrUndefined(provider);
RequireRatchet.notNullOrUndefined(cfg);
}
async getConfig(name) {
Logger.silly('EnvService:Request to read config %s', name);
if (!this.readPromiseCache.has(name)) {
Logger.silly('EnvService: Nothing in cache - adding');
this.readPromiseCache.set(name, this.getConfigUncached(name));
}
return this.readPromiseCache.get(name);
}
async fetchConfigValueByPath(cfgName, path) {
RequireRatchet.notNullUndefinedOrOnlyWhitespaceString(cfgName);
RequireRatchet.notNullUndefinedOrEmptyArray(path);
const env = await this.getConfig(cfgName);
if (!env) {
throw ErrorRatchet.fErr('No config found with name ', cfgName);
}
let rval = env;
for (const p of path) {
rval = rval ? rval[p] : null;
}
if (!rval) {
throw ErrorRatchet.fErr('No value found in %s for path %s', cfgName, path);
}
return rval;
}
async getConfigUncached(name) {
let tryCount = 1;
let rval = null;
while (!rval && tryCount < this.cfg.maxRetries) {
tryCount++;
Logger.silly('Attempting fetch of %s', name);
try {
rval = await this.provider.fetchConfig(name);
}
catch (err) {
const waitMS = tryCount * this.cfg.backoffMultiplierMS;
Logger.info('Error attempting to fetch config %s (try %d of %d, waiting %s MS): %s', name, tryCount, this.cfg.maxRetries, waitMS, err, err);
await PromiseRatchet.wait(waitMS);
}
}
if (!rval) {
ErrorRatchet.throwFormattedErr('Was unable to fetch config %s even after %d retries', name, this.cfg.maxRetries);
}
return rval;
}
}
//# sourceMappingURL=environment-service.js.map