patternjavascriptMinor
Node.JS module to retrieve configuration from environment variables
Viewed 0 times
nodemoduleconfigurationenvironmentretrievevariablesfrom
Problem
I don't like the idea of sprinkling process.env all over the place and wanted to abstract it out a bit. I'm new to Node and know there must be a better way to do a few things.
- Not repeat the name 4 times (twice as a string and twice as a field)
- Any cleaner way to create properties and centralize existence checks than how I've done it? Mind you, I am trying to keep this Node 4.3.2 compatible sans Babel transpilers to keep it simple and working in AWS Lambda's NodeJs environment.
// module
module.exports = {
}
var configError = function (keyName) {
console.error("ExternalVars error! Could not load a value for: "+keyName);
process.exit(1);
}
// TODO: extract repeated function?
Object.defineProperty(module.exports, 'SAMPLE_SECRET', {
get: function() {
if (!process.env.SAMPLE_SECRET)
configError('SAMPLE_SECRET');
else
return process.env.SAMPLE_SECRET;
}
});
Object.defineProperty(module.exports, 'SAMPLE_SECRET_MORE', {
get: function() {
if (!process.env.SAMPLE_SECRET_MORE)
configError('SAMPLE_SECRET_MORE');
else
return process.env.SAMPLE_SECRET_MORE;
}
});
// usage example
var externalvars = require('./config/externalvars.js');
var sampleSecret = externalvars.SAMPLE_SECRET;
var sampleSecretMore = externalvars.SAMPLE_SECRET_MORE;Solution
Disclaimer: since I'm not familiar with export/import realm, my suggestion below might be too naive and not work. If so, rather than only downvoting, thanks in advance for a little comment pointing me to a resource which would enlight how and why I'm wrong.
That's said, with merely my pure JS skills, here is how I'd work:
That's said, with merely my pure JS skills, here is how I'd work:
var keys = [
'SAMPLE_SECRET',
'SAMPLE_SECRET_MORE'
];
keys.forEach(function(keyName) {
Object.defineProperty(module.exports, keyName, {
get: function() {
if (!process.env[keyName]) {
console.error(
"ExternalVars error! Could not load a value for: " + keyName
);
process.exit(1);
} else {
return process.env[keyName];
}
}
});
});Code Snippets
var keys = [
'SAMPLE_SECRET',
'SAMPLE_SECRET_MORE'
];
keys.forEach(function(keyName) {
Object.defineProperty(module.exports, keyName, {
get: function() {
if (!process.env[keyName]) {
console.error(
"ExternalVars error! Could not load a value for: " + keyName
);
process.exit(1);
} else {
return process.env[keyName];
}
}
});
});Context
StackExchange Code Review Q#148190, answer score: 2
Revisions (0)
No revisions yet.