From 5b7e1df53c92cc2f5b3d58102f8f1f040d5aca3e Mon Sep 17 00:00:00 2001 From: Stephen Hess Date: Wed, 3 May 2017 14:43:30 -0400 Subject: [PATCH] generated now returns validated config with defaults and types massaged --- index.js | 13 ++++++++----- test/generate.js | 24 ++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/index.js b/index.js index 17407d8..1ef9ff5 100644 --- a/index.js +++ b/index.js @@ -23,11 +23,14 @@ var generate = function( schema, deep ){ const config = getConfig(deep); if (_.isObject(schema)) { - Joi.validate(config, schema, (err) => { - if (err) { - throw new Error(err.details[0].message); - } - }); + const result = Joi.validate(config, schema); + + if (result.error) { + throw new Error(result.error.details[0].message); + } + + return result.value; + } return config; diff --git a/test/generate.js b/test/generate.js index 9c5abe8..b699e57 100644 --- a/test/generate.js +++ b/test/generate.js @@ -201,6 +201,30 @@ module.exports.generate.validate = (test) => { }); + test('returned config should have defaults applied and types converted', (t) => { + const localConfig = require('../'); + localConfig.defaults.test = { + key_with_type_conversion: 'yes' + }; + + const schema = Joi.object().keys({ + test: Joi.object().keys({ + key_with_default: Joi.string().default('default value'), + key_with_type_conversion: Joi.boolean().default(true).truthy('yes').falsy('no'), + key_without_default: Joi.string() + }) + }).unknown(true); + + const validatedConfig = localConfig.generate(schema); + + t.equals(validatedConfig.test.key_with_default, 'default value', 'default value should be used'); + t.ok(typeof validatedConfig.test.key_with_type_conversion, 'boolean', 'should be boolean'); + t.ok(validatedConfig.test.key_with_type_conversion, 'should be true'); + t.equals(validatedConfig.test.key_without_default, undefined, 'no default'); + t.end(); + + }); + }; module.exports.all = function (tape) {