diff options
author | Samy Pessé <samypesse@gmail.com> | 2016-04-22 11:33:25 +0200 |
---|---|---|
committer | Samy Pessé <samypesse@gmail.com> | 2016-04-22 11:33:25 +0200 |
commit | cc78b880cef726201f1670b5c9f7f6f3512c2dbe (patch) | |
tree | 2e41e8bf387b1f1efc5a78aa71e0369550cad495 /lib/plugins/validateConfig.js | |
parent | 4336fdb2414d460ffee68a0cc87c0cb0c85cf56e (diff) | |
download | gitbook-cc78b880cef726201f1670b5c9f7f6f3512c2dbe.zip gitbook-cc78b880cef726201f1670b5c9f7f6f3512c2dbe.tar.gz gitbook-cc78b880cef726201f1670b5c9f7f6f3512c2dbe.tar.bz2 |
Add utils to install plugins
Diffstat (limited to 'lib/plugins/validateConfig.js')
-rw-r--r-- | lib/plugins/validateConfig.js | 70 |
1 files changed, 70 insertions, 0 deletions
diff --git a/lib/plugins/validateConfig.js b/lib/plugins/validateConfig.js new file mode 100644 index 0000000..fc32344 --- /dev/null +++ b/lib/plugins/validateConfig.js @@ -0,0 +1,70 @@ +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, {}); + + var schema = packageInfos.gitbook || {}; + 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(config, 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(config, 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; |