diff options
author | Samy Pesse <samypesse@gmail.com> | 2016-04-30 20:15:08 +0200 |
---|---|---|
committer | Samy Pesse <samypesse@gmail.com> | 2016-04-30 20:15:08 +0200 |
commit | 36b49c66c6b75515bc84dd678fd52121a313e8d2 (patch) | |
tree | bc7e0f703d4557869943ec7f9495cac7a5027d4f /lib/plugins/validateConfig.js | |
parent | 87db7cf1d412fa6fbd18e9a7e4f4755f2c0c5547 (diff) | |
parent | 80b8e340dadc54377ff40500f86b1de631395806 (diff) | |
download | gitbook-36b49c66c6b75515bc84dd678fd52121a313e8d2.zip gitbook-36b49c66c6b75515bc84dd678fd52121a313e8d2.tar.gz gitbook-36b49c66c6b75515bc84dd678fd52121a313e8d2.tar.bz2 |
Merge branch 'fixes'
Diffstat (limited to 'lib/plugins/validateConfig.js')
-rw-r--r-- | lib/plugins/validateConfig.js | 71 |
1 files changed, 71 insertions, 0 deletions
diff --git a/lib/plugins/validateConfig.js b/lib/plugins/validateConfig.js new file mode 100644 index 0000000..37f3c96 --- /dev/null +++ b/lib/plugins/validateConfig.js @@ -0,0 +1,71 @@ +var Immutable = require('immutable'); +var jsonschema = require('jsonschema'); +var jsonSchemaDefaults = require('json-schema-defaults'); +var mergeDefaults = require('merge-defaults'); + +var Promise = require('../utils/promise'); +var error = require('../utils/error'); + +/** + Validate one plugin for a book and update book's confiration + + @param {Book} + @param {Plugin} + @return {Book} +*/ +function validatePluginConfig(book, plugin) { + var config = book.getConfig(); + var packageInfos = plugin.getPackage(); + + var configKey = [ + 'pluginsConfig', + plugin.getName() + ].join('.'); + + var pluginConfig = config.getValue(configKey, {}).toJS(); + + var schema = (packageInfos.get('gitbook') || Immutable.Map()).toJS(); + if (!schema) return book; + + // Normalize schema + schema.id = '/' + configKey; + schema.type = 'object'; + + // Validate and throw if invalid + var v = new jsonschema.Validator(); + var result = v.validate(pluginConfig, schema, { + propertyName: configKey + }); + + // Throw error + if (result.errors.length > 0) { + throw new error.ConfigurationError(new Error(result.errors[0].stack)); + } + + // Insert default values + var defaults = jsonSchemaDefaults(schema); + pluginConfig = mergeDefaults(pluginConfig, defaults); + + + // Update configuration + config = config.setValue(configKey, pluginConfig); + + // Return new book + return book.set('config', config); +} + +/** + Validate a book configuration for plugins and + returns an update configuration with default values. + + @param {Book} + @param {OrderedMap<String:Plugin>} + @return {Promise<Book>} +*/ +function validateConfig(book, plugins) { + return Promise.reduce(plugins, function(newBook, plugin) { + return validatePluginConfig(newBook, plugin); + }, book); +} + +module.exports = validateConfig; |