Last active
October 17, 2020 07:03
-
-
Save chiro-hiro/258e5535e7c16aa55f662ce0617697bf to your computer and use it in GitHub Desktop.
Protect environment variables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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