Last active
July 25, 2017 19:16
-
-
Save donpayne/ef239d8227a737d019a7bc02d899cf02 to your computer and use it in GitHub Desktop.
Javascript native config object using proxy and eventEmitter
This file contains hidden or 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
import { EventEmitter } from 'events'; | |
let listener = new EventEmitter(); | |
let config = new Proxy(filteredEnvVars(), { get, set }); | |
export default Object.assign(config, { listener }); | |
function filteredEnvVars () { | |
return Object.keys(process.env) | |
.filter(removeNPMVars) | |
.reduce(assignToObject, {}); | |
} | |
function removeNPMVars (key) { | |
return !key.includes('npm_'); | |
} | |
function assignToObject (obj, key) { | |
return Object.assign(obj, { [key]: process.env[key] }); | |
} | |
function get (target, key) { | |
return target[key]; | |
} | |
function set (target, key, val) { | |
validate(key, val, 'set'); | |
listener.emit(`${key}.set`, val); | |
return Object.assign(target, { [key]: val }); | |
} | |
function validate (key, val, action) { | |
if (val === undefined) { | |
throw new Error(`Invalid attempt to ${action} "${key}" to undefined.`); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment