@bitblit/ratchet-common
Version:
Common tools for general use
90 lines • 2.87 kB
JavaScript
import { RequireRatchet } from './require-ratchet.js';
export class GlobalRatchet {
constructor() { }
static globalExists() {
return typeof global !== 'undefined';
}
static windowExists() {
return typeof window !== 'undefined';
}
static processExists() {
return typeof process !== 'undefined';
}
static fetchGlobalVarsRecord(returnNullOnNone) {
let rval = null;
try {
if (GlobalRatchet.globalExists()) {
rval = global;
}
else if (GlobalRatchet.windowExists()) {
rval = window;
}
else if (GlobalRatchet.processExists()) {
rval = process;
}
}
catch (err) {
throw new Error('Should not happen - error thrown trying to find global : ' + err);
}
if (!rval) {
if (returnNullOnNone) {
rval = null;
}
else {
throw new Error('Could not find global, process, or window in scope');
}
}
return rval;
}
static fetchGlobalVar(key, defValue) {
const rec = GlobalRatchet.fetchGlobalVarsRecord(false);
let rval = rec[key];
if (!rval && defValue) {
rec[key] = defValue;
rval = defValue;
}
return rval;
}
static setGlobalVar(key, val) {
const rec = GlobalRatchet.fetchGlobalVarsRecord(false);
rec[key] = val;
}
static fetchGlobalEnvVarRecord(returnNullOnNone) {
let rval = null;
if (GlobalRatchet.processExists() && process?.env) {
rval = process.env;
}
else if (GlobalRatchet.globalExists() && global?.process?.env) {
rval = global.process.env;
}
else if (GlobalRatchet.globalExists()) {
rval = global;
}
else if (GlobalRatchet.windowExists()) {
rval = window;
}
if (!rval) {
if (returnNullOnNone) {
rval = null;
}
else {
throw new Error('Could not find process.env OR global OR window in scope');
}
}
return rval;
}
static fetchGlobalEnvVar(envVar) {
RequireRatchet.notNullOrUndefined(envVar, 'envVar');
const myGlobal = GlobalRatchet.fetchGlobalEnvVarRecord();
const value = myGlobal[envVar];
const sValue = value ? String(value) : value;
return sValue;
}
static setGlobalEnvVar(envVar, value) {
RequireRatchet.notNullOrUndefined(envVar, 'envVar');
RequireRatchet.notNullOrUndefined(value, 'value');
const myGlobal = GlobalRatchet.fetchGlobalEnvVarRecord();
myGlobal[envVar] = value;
}
}
//# sourceMappingURL=global-ratchet.js.map