Skip to content

Instantly share code, notes, and snippets.

@taxilian
Created February 3, 2022 20:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save taxilian/dbd04ae2366040e35ca8db0ab7d8e740 to your computer and use it in GitHub Desktop.
Save taxilian/dbd04ae2366040e35ca8db0ab7d8e740 to your computer and use it in GitHub Desktop.
Env overrides for config
import _ from 'lodash';
const ENV_PREFIX = `APP_CONFIG`;
function setEnvOverrides(cfg: Config) {
const foundVars = Object.keys(process.env).filter(name => name.startsWith(ENV_PREFIX));
for (const v of foundVars) {
const actualName = v.substr(ENV_PREFIX.length);
// console.log(`Processing ENV var ${actualName}`);
const pieces = actualName.split('_');
const oldVal: any = _.get(cfg, pieces, void 0);
const envVal = process.env[v].trim();
if (typeof oldVal == 'number') {
_.set(cfg, pieces, Number(envVal));
} else if (typeof oldVal == 'boolean') {
try {
_.set(config, pieces, Boolean(JSON.parse(envVal.toLowerCase())));
} catch (err) {
console.warn(`Igoring ENV var ${actualName}; did not parse to boolean`);
}
} else {
// Anything else we'll just treat as a string
_.set(cfg, pieces, envVal);
}
}
return cfg;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment