Skip to content

Commit

Permalink
feat: Merge pull request #57 from pelias/return-joi-sanitized-config-…
Browse files Browse the repository at this point in the history
…from-schema

generated now returns validated config with defaults and types massaged
  • Loading branch information
trescube authored May 3, 2017
2 parents ab40917 + 5b7e1df commit 9815c2e
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 5 deletions.
13 changes: 8 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
24 changes: 24 additions & 0 deletions test/generate.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit 9815c2e

Please sign in to comment.