From 37a84ae8dffe7cff3e07ef8bc525879ed859ec66 Mon Sep 17 00:00:00 2001 From: Wojtek Turyn Date: Thu, 15 Oct 2015 10:16:33 +0200 Subject: [PATCH 1/2] required() method --- lib/nconf/provider.js | 25 +++++++++++++++++++++++++ test/nconf-test.js | 11 +++++++++++ 2 files changed, 36 insertions(+) diff --git a/lib/nconf/provider.js b/lib/nconf/provider.js index d35b820..5e39e38 100644 --- a/lib/nconf/provider.js +++ b/lib/nconf/provider.js @@ -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. diff --git a/test/nconf-test.js b/test/nconf-test.js index f0fce79..89bfab9 100644 --- a/test/nconf-test.js +++ b/test/nconf-test.js @@ -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 () { @@ -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({ From 5d6e236b73da3336fa3337db1c99d80c1c0ac963 Mon Sep 17 00:00:00 2001 From: Wojtek Turyn Date: Thu, 15 Oct 2015 10:44:26 +0200 Subject: [PATCH 2/2] fixed --- test/nconf-test.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/nconf-test.js b/test/nconf-test.js index 89bfab9..ba6c75c 100644 --- a/test/nconf-test.js +++ b/test/nconf-test.js @@ -46,7 +46,7 @@ vows.describe('nconf').addBatch({ "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); + assert.throws(nconf.required.bind(nconf, ['missing', 'foo:bar:bazz']), Error); }, "should return true if all required keys exist": function() { nconf.set('foo:bar:bazz', 'buzz');