Skip to content

Instantly share code, notes, and snippets.

@lukekarrys
Created November 7, 2019 18:54
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 lukekarrys/5521a50446e8ce5dcdabb9786b89b3b9 to your computer and use it in GitHub Desktop.
Save lukekarrys/5521a50446e8ce5dcdabb9786b89b3b9 to your computer and use it in GitHub Desktop.
Constants Proxy
module.exports = (keys) => new Proxy(
keys.reduce((acc, key) => ((acc[key] = key), acc), {}),
{
get: function(target, name) {
// Since this getter gets called for all keys, some values need to be ignored
if (
// If this proxy gets logged or inspected then name
// could be a symbol or the string inspect
typeof name === 'symbol' ||
name === 'inspect' ||
// In a babel/webpack env, this string gets read from the resulting export
name === '__esModule'
) {
return
}
// If it is one of our constant values, then yay! return it
if (Object.prototype.hasOwnProperty.call(target, name)) {
return target[name]
}
// Otherwise log (in a browser) or error (on the server)
const message = `No ${name} constant exists`
if (typeof window !== 'undefined') {
// eslint-disable-next-line no-console
console.error(message)
} else {
throw new Error(message)
}
},
set: function() {
// No setting allowed after the module gets exported
throw new Error(`Can't set constant value during runtime`)
}
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment