Skip to content
This repository has been archived by the owner on Jul 16, 2023. It is now read-only.

Commit

Permalink
feat(config): ✨ support for setting up config using env vars
Browse files Browse the repository at this point in the history
  • Loading branch information
filipowm committed Jun 3, 2020
1 parent 6baf02e commit e611e4b
Showing 1 changed file with 54 additions and 1 deletion.
55 changes: 54 additions & 1 deletion config/config-reader.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,61 @@ class FileReader extends ConfigReader {

class EnvReader extends ConfigReader {

readArray(key) {
const value = this.readValue(key);
if (value) {
return value.split(',')
.map(String.trim);
}
return value;
}

readValue(key) {
if (key in process.env) {
const value = process.env[key]
try {
return value === "true" ? true : value === "false" ? false : parseFloat(value);
} catch(err) {
return value;
}
}
return undefined;
}

generatePrefix(prefix, key) {
const suffix = key.split(/(?=[A-Z])/)
.map((str) => str.toUpperCase())
.join("_");
return prefix !== "" ? `${prefix}_${suffix}` : suffix;
}

readObject(obj, config, prefix) {
for (let [key, value] of Object.entries(obj)) {
const newPrefix = this.generatePrefix(prefix, key);
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean" || value === null) {
const value = this.readValue(newPrefix)
if (value !== undefined) {
config[key] = value
}
} else if (typeof value === "object") {
if (Array.isArray(value)) {
const value = this.readArray(newPrefix)
if (value !== undefined) {
config[key] = value
}
} else {
const child = {}
config[key] = child;
this.readObject(value, child, newPrefix)
}
}
}
}

read() {
return {};
const config = {};
this.readObject(defaults, config, "");
return config;
}
}

Expand Down

0 comments on commit e611e4b

Please sign in to comment.