UI for Zipcoin Blue

validateSchema.js 1.5KB

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