Skip to content

Instantly share code, notes, and snippets.

@ericblade
Created September 18, 2018 10:11
Show Gist options
  • Save ericblade/2cc866f32a17f7c9076713a4ace2fb4a to your computer and use it in GitHub Desktop.
Save ericblade/2cc866f32a17f7c9076713a4ace2fb4a to your computer and use it in GitHub Desktop.
node.js 6+ function for erroring when accessing an undefined property on an object, useful for application constant includes and such
constants.js:
function disallowUndefinedAccess(obj) {
const handler = {
get(target, property) {
if (property in target) {
return target[property];
}
throw new ReferenceError(`Access unknown ${property.toString()}`);
},
};
return new Proxy(obj, handler);
}
... define a bunch of constants, such as error messages, urls, file paths, constant service responses, things like that
module.exports = disallowUndefinedAccess({
...all the things you would export
});
in another file:
const c = require('constants.js');
console.warn(c.SOMETHING_NOT_IN_LIST);
-> ReferenceError: Access unknown SOMETHING_NOT_IN_LIST
Very useful when you are refactoring a bunch of things. :-D
We also use a similar paradigm in front-end development, where
import { ABC } from './constants.js';
console.warn(ABC);
throws an error if constants.js does not actually export an ABC.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment