Skip to content

Commit

Permalink
Read from object should be available on existing config objects.
Browse files Browse the repository at this point in the history
  • Loading branch information
Mat Carey committed Mar 30, 2015
1 parent 3f7e875 commit 07c6141
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 20 deletions.
14 changes: 14 additions & 0 deletions spec/usageExamplesSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,20 @@ describe('Usage Examples', function () {
someRandomThing: 'value B'
});
});
it('should also be available on instantiated config objects', function () {
process.env.SOME_PREFIX__MY_VAR = 'value A';
process.env.SOME_PREFIX__ANOTHER_VAR = 'value B';
var actual = new JsConfig({firstValue: 'set in constructor'});
actual.readFromObject(process.env, {
myVar: 'SOME_PREFIX__MY_VAR',
someRandomThing: 'SOME_PREFIX__ANOTHER_VAR'
});
expect(actual.getAll()).toEqual({
firstValue: 'set in constructor',
myVar: 'value A',
someRandomThing: 'value B'
});
});
it('should remap string values into hierarchy', function () {
process.env.SOME_PREFIX__MY_VAR = 'value A';
process.env.SOME_PREFIX__ANOTHER_VAR = 'value B';
Expand Down
41 changes: 21 additions & 20 deletions src/JsConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -115,29 +115,30 @@ var JsConfig = (function () {
delete data[key];
}
};
}

JsConfig.readFromObject = function (obj, items) {
var missingKeys = [], output = new JsConfig();

function deepLoop(parent, combinedName) {
loop(parent, function (value, key) {
var name = combinedName ? combinedName + '.' : '';
name += key;
if (typeof value === 'object') {
deepLoop(value, name);
} else {
if (obj.hasOwnProperty(value)) {
output.set(name, obj[value]);
this.readFromObject = function (obj, items) {
var self = this;
function deepLoop(parent, combinedName) {
loop(parent, function (value, key) {
var name = combinedName ? combinedName + '.' : '';
name += key;
if (typeof value === 'object') {
deepLoop(value, name);
} else {
if (obj.hasOwnProperty(value)) {
self.set(name, obj[value]);
}
}
}
});
}
});
}

deepLoop(items || {});
if (missingKeys.length > 0) {
throw new Error('Missing required configuration parameter [' + missingKeys.join(',') + '].');
}
deepLoop(items || {});
};
}

JsConfig.readFromObject = function () {
var output = new JsConfig();
output.readFromObject.apply(output, arguments);
return output;
};

Expand Down

0 comments on commit 07c6141

Please sign in to comment.