Jsv.js

  1. import defaultConfig, { Config } from './config';
  2. import validate from './validate';
  3. import loadValidators from './validatorsLoader';
  4. import loadTransformers from './transformersLoader';
  5. export function createJSV(_config) {
  6. if (_config == null) {
  7. _config = new Config();
  8. loadValidators(_config);
  9. loadTransformers(_config);
  10. }
  11. /**
  12. * JSON Validation Syntax
  13. * @class
  14. */
  15. class JSV {
  16. static get config() {
  17. return _config;
  18. }
  19. static match(value, jsv, options, context) {
  20. const reason = validate(
  21. value,
  22. jsv,
  23. {
  24. throwError: false,
  25. abortEarly: true,
  26. plainError: true,
  27. ...options,
  28. },
  29. { config: this.config, ...context }
  30. );
  31. if (reason === true) {
  32. return [true];
  33. }
  34. return [false, reason];
  35. }
  36. /**
  37. * @param {object} value
  38. */
  39. constructor(value) {
  40. this.value = value;
  41. }
  42. /**
  43. * Match the value with expected conditions in JSON expression
  44. * @param {object} expected - JSON match expression
  45. * @throws ValidationError
  46. * @returns {JSV}
  47. */
  48. match(expected) {
  49. validate(this.value, expected, { throwError: true, abortEarly: true }, { config: this.constructor.config });
  50. return this;
  51. }
  52. }
  53. return JSV;
  54. }
  55. loadValidators(defaultConfig);
  56. loadTransformers(defaultConfig);
  57. const defaultJSV = createJSV(defaultConfig);
  58. export default defaultJSV;