Created
November 7, 2019 18:54
-
-
Save lukekarrys/5521a50446e8ce5dcdabb9786b89b3b9 to your computer and use it in GitHub Desktop.
Constants Proxy
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
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