Enable support for parsing JSON environment variables (#272)

* Add support for applying JSON string

* only take JSON Object or JSON Array into consideration

* Add tests and make JSON-parsing opt-in
master
Matt Hamann 2017-09-27 16:32:26 -04:00 committed by GitHub
parent f46c449a9e
commit b8402d4eab
2 changed files with 61 additions and 2 deletions

View File

@ -24,6 +24,7 @@ var Env = exports.Env = function (options) {
this.whitelist = options.whitelist || [];
this.separator = options.separator || '';
this.lowerCase = options.lowerCase || false;
this.parseJson = options.parseJson || false;
if (({}).toString.call(options.match) === '[object RegExp]'
&& typeof options !== 'string') {
@ -78,11 +79,31 @@ Env.prototype.loadEnv = function () {
return !self.whitelist.length || self.whitelist.indexOf(key) !== -1
}
}).forEach(function (key) {
var val = env[key];
if (self.parseJson) {
try {
var ret = JSON.parse(val);
// apply JSON parsing only if its non-primitive types: JSON Object or Array
// avoid breaking backward-compatibility
if (typeof ret !== 'number' &&
typeof ret !== 'string' &&
typeof ret !== 'boolean') {
val = ret;
}
} catch (ignore) {
//ignore
}
}
if (self.separator) {
self.set(common.key.apply(common, key.split(self.separator)), env[key]);
self.set(common.key.apply(common, key.split(self.separator)), val);
}
else {
self.set(key, env[key]);
self.set(key, val);
}
});

View File

@ -22,6 +22,8 @@ process.env.FOO = 'bar';
process.env.BAR = 'zalgo';
process.env.NODE_ENV = 'debug';
process.env.FOOBAR = 'should not load';
process.env.json_array = JSON.stringify(['foo', 'bar', 'baz']);
process.env.json_obj = JSON.stringify({foo: 'bar', baz: 'foo'});
vows.describe('nconf/multiple-stores').addBatch({
"When using the nconf with multiple providers": {
@ -156,4 +158,40 @@ vows.describe('nconf/multiple-stores').addBatch({
nconf.remove('env');
}
}
}).addBatch({
// Threw this in it's own batch to make sure it's run separately from the
// sync check
"When using env with parseJson:true": {
topic: function () {
var that = this;
helpers.cp(complete, completeTest, function () {
nconf.env({ parseJson: true });
that.callback();
});
},
"env vars": {
"JSON keys properly parsed": function () {
Object.keys(process.env).forEach(function (key) {
var val = process.env[key];
try {
var ret = JSON.parse(val);
// apply JSON parsing only if its non-primitive types: JSON Object or Array
// avoid breaking backward-compatibility
if (typeof ret !== 'number' &&
typeof ret !== 'string' &&
typeof ret !== 'boolean') {
val = ret;
}
} catch (err) {}
assert.deepEqual(nconf.get(key), val);
});
}
},
teardown: function () {
nconf.remove('env');
}
}
}).export(module);