2016-09-09 00:42:26 +08:00
|
|
|
/*
|
|
|
|
MIT License http://www.opensource.org/licenses/mit-license.php
|
|
|
|
Author Gajus Kuizinas @gajus
|
|
|
|
*/
|
|
|
|
var Ajv = require("ajv");
|
2016-09-19 06:54:35 +08:00
|
|
|
var ajv = new Ajv({
|
|
|
|
errorDataPath: "configuration",
|
|
|
|
allErrors: true,
|
|
|
|
verbose: true
|
|
|
|
});
|
2016-12-14 18:34:31 +08:00
|
|
|
require("ajv-keywords")(ajv);
|
2016-09-19 06:54:35 +08:00
|
|
|
|
2016-11-03 21:52:09 +08:00
|
|
|
function validateSchema(schema, options) {
|
2016-09-19 06:54:35 +08:00
|
|
|
if(Array.isArray(options)) {
|
2016-11-01 22:32:00 +08:00
|
|
|
var errors = options.map(validateObject.bind(this, schema));
|
2016-09-19 06:54:35 +08:00
|
|
|
errors.forEach(function(list, idx) {
|
|
|
|
list.forEach(function applyPrefix(err) {
|
|
|
|
err.dataPath = "[" + idx + "]" + err.dataPath;
|
|
|
|
if(err.children) {
|
|
|
|
err.children.forEach(applyPrefix);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
});
|
|
|
|
return errors.reduce(function(arr, items) {
|
|
|
|
return arr.concat(items);
|
|
|
|
}, []);
|
|
|
|
} else {
|
2016-11-02 06:38:54 +08:00
|
|
|
return validateObject(schema, options);
|
2016-09-19 06:54:35 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-11-02 06:38:54 +08:00
|
|
|
function validateObject(schema, options) {
|
2016-11-01 22:32:00 +08:00
|
|
|
var validate = ajv.compile(schema);
|
2016-09-09 00:42:26 +08:00
|
|
|
var valid = validate(options);
|
2016-09-19 06:54:35 +08:00
|
|
|
return valid ? [] : filterErrors(validate.errors);
|
|
|
|
}
|
|
|
|
|
|
|
|
function filterErrors(errors) {
|
|
|
|
var newErrors = [];
|
|
|
|
errors.forEach(function(err) {
|
|
|
|
var dataPath = err.dataPath;
|
2016-12-14 18:34:31 +08:00
|
|
|
var children = [];
|
|
|
|
newErrors = newErrors.filter(function(oldError) {
|
|
|
|
if(oldError.dataPath.indexOf(dataPath) >= 0) {
|
|
|
|
if(oldError.children) {
|
|
|
|
oldError.children.forEach(function(child) {
|
|
|
|
children.push(child);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
oldError.children = undefined;
|
2016-09-19 06:54:35 +08:00
|
|
|
children.push(oldError);
|
2016-12-14 18:34:31 +08:00
|
|
|
return false;
|
2016-09-19 06:54:35 +08:00
|
|
|
}
|
2016-12-14 18:34:31 +08:00
|
|
|
return true;
|
|
|
|
});
|
|
|
|
if(children.length) {
|
|
|
|
err.children = children;
|
2016-09-19 06:54:35 +08:00
|
|
|
}
|
|
|
|
newErrors.push(err);
|
|
|
|
});
|
2016-12-14 18:34:31 +08:00
|
|
|
//console.log(JSON.stringify(newErrors, 0, 2));
|
2016-09-19 06:54:35 +08:00
|
|
|
return newErrors;
|
2016-09-09 00:42:26 +08:00
|
|
|
}
|
2016-09-19 06:54:35 +08:00
|
|
|
|
2016-11-03 21:52:09 +08:00
|
|
|
module.exports = validateSchema;
|