1
|
/*
|
2
|
MIT License http://www.opensource.org/licenses/mit-license.php
|
3
|
Author Gajus Kuizinas @gajus
|
4
|
*/
|
5
|
"use strict";
|
6
|
|
7
|
const Ajv = require("ajv");
|
8
|
const ajv = new Ajv({
|
9
|
errorDataPath: "configuration",
|
10
|
allErrors: true,
|
11
|
verbose: true
|
12
|
});
|
13
|
require("ajv-keywords")(ajv, ["instanceof"]);
|
14
|
require("../schemas/ajv.absolutePath")(ajv);
|
15
|
|
16
|
const validateSchema = (schema, options) => {
|
17
|
if (Array.isArray(options)) {
|
18
|
const errors = options.map(options => validateObject(schema, options));
|
19
|
errors.forEach((list, idx) => {
|
20
|
const applyPrefix = err => {
|
21
|
err.dataPath = `[${idx}]${err.dataPath}`;
|
22
|
if (err.children) {
|
23
|
err.children.forEach(applyPrefix);
|
24
|
}
|
25
|
};
|
26
|
list.forEach(applyPrefix);
|
27
|
});
|
28
|
return errors.reduce((arr, items) => {
|
29
|
return arr.concat(items);
|
30
|
}, []);
|
31
|
} else {
|
32
|
return validateObject(schema, options);
|
33
|
}
|
34
|
};
|
35
|
|
36
|
const validateObject = (schema, options) => {
|
37
|
const validate = ajv.compile(schema);
|
38
|
const valid = validate(options);
|
39
|
return valid ? [] : filterErrors(validate.errors);
|
40
|
};
|
41
|
|
42
|
const filterErrors = errors => {
|
43
|
let newErrors = [];
|
44
|
for (const err of errors) {
|
45
|
const dataPath = err.dataPath;
|
46
|
let children = [];
|
47
|
newErrors = newErrors.filter(oldError => {
|
48
|
if (oldError.dataPath.includes(dataPath)) {
|
49
|
if (oldError.children) {
|
50
|
children = children.concat(oldError.children.slice(0));
|
51
|
}
|
52
|
oldError.children = undefined;
|
53
|
children.push(oldError);
|
54
|
return false;
|
55
|
}
|
56
|
return true;
|
57
|
});
|
58
|
if (children.length) {
|
59
|
err.children = children;
|
60
|
}
|
61
|
newErrors.push(err);
|
62
|
}
|
63
|
|
64
|
return newErrors;
|
65
|
};
|
66
|
|
67
|
module.exports = validateSchema;
|