Skip to content

Instantly share code, notes, and snippets.

@chiro-hiro
Last active October 17, 2020 07:03
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 chiro-hiro/258e5535e7c16aa55f662ce0617697bf to your computer and use it in GitHub Desktop.
Save chiro-hiro/258e5535e7c16aa55f662ce0617697bf to your computer and use it in GitHub Desktop.
Protect environment variables
function uFirst(v) {
return v.length > 0 ? `${v[0].toUpperCase()}${v.substr(1)}` : "";
}
function toCamelCase(v) {
return v
.toLowerCase()
.split("_")
.map((e, i) => (i > 0 ? uFirst(e.trim()) : e.toLowerCase()))
.join("");
}
var conf = null;
var exportedConf = null;
module.exports = (() => {
if (exportedConf !== null) {
return exportedConf;
}
conf = conf || {};
// Clone basic env
const cachedEnv = { ...process.env };
// Load env file
require("dotenv").config();
let keys = Object.keys(process.env);
// Copy data to private conf
for (let i = 0; i < keys.length; i += 1) {
let key = keys[i];
conf[toCamelCase(key)] = process.env[key];
// Delete all keys from .env file
if (typeof cachedEnv[key] === "undefined") {
delete process.env[key];
}
}
exportedConf = new Proxy(conf, {
get(target, prop, receiver) {
if (typeof target[prop] !== "undefined") {
return Reflect.get(target, prop, receiver);
}
throw new Error(`You are trying to access undefined key`);
},
set: () => {
throw new Error(`You can not set value to immutable object`);
},
has: () => false,
ownKeys: () => [],
});
return exportedConf;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment