Skip to content

Commit

Permalink
required() method
Browse files Browse the repository at this point in the history
  • Loading branch information
Wojtek Turyn committed Oct 15, 2015
1 parent ddee9bc commit 37a84ae
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
25 changes: 25 additions & 0 deletions lib/nconf/provider.js
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,31 @@ Provider.prototype.set = function (key, value, callback) {
return this._execute('set', 2, key, value, callback);
};


//
// ### function required (keys)
// #### @keys {array} List of keys
// Throws an error if any of `keys` has no value, otherwise returns `true`
Provider.prototype.required = function (keys) {
if (!Array.isArray(keys)) {
throw new Error('Incorrect parameter, array expected');
}

var missing = [];
keys.forEach(function(key) {
if (typeof this.get(key) === 'undefined') {
missing.push(key);
}
}, this);

if (missing.length) {
throw new Error('Missing required keys: ' + missing.join(', '));
} else {
return true;
}

};

//
// ### function reset (callback)
// #### @callback {function} **Optional** Continuation to respond to when complete.
Expand Down
11 changes: 11 additions & 0 deletions test/nconf-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ vows.describe('nconf').addBatch({
assert.isFunction(nconf.load);
assert.isFunction(nconf.save);
assert.isFunction(nconf.reset);
assert.isFunction(nconf.required);
},
"the use() method": {
"should instaniate the correct store": function () {
Expand All @@ -41,6 +42,16 @@ vows.describe('nconf').addBatch({
data = JSON.parse(data.toString());
assert.equal(nconf.version, data.version);
}
},
"the required() method": {
"should throw error with missing keys": function() {
nconf.set('foo:bar:bazz', 'buzz');
assert.throws(nconf.required.bind(null, ['missingkey', 'foo:bar:bazz']), Error);
},
"should return true if all required keys exist": function() {
nconf.set('foo:bar:bazz', 'buzz');
assert.isTrue(nconf.required(['foo:bar:bazz']));
}
}
}
}).addBatch({
Expand Down

0 comments on commit 37a84ae

Please sign in to comment.