index.js 1018 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import Ajv from 'ajv/dist/2020.js';
  2. import _ from "lodash";
  3. import commonDefinitions from "../../schema/common.json" with { type: "json" };
  4. import errs from "../error.js";
  5. RegExp.prototype.toJSON = RegExp.prototype.toString;
  6. const ajv = new Ajv({
  7. verbose: true,
  8. allErrors: true,
  9. allowUnionTypes: true,
  10. coerceTypes: true,
  11. strict: false,
  12. schemas: [commonDefinitions],
  13. });
  14. /**
  15. *
  16. * @param {Object} schema
  17. * @param {Object} payload
  18. * @returns {Promise}
  19. */
  20. const validator = (schema, payload) => {
  21. return new Promise((resolve, reject) => {
  22. if (!payload) {
  23. reject(new errs.InternalValidationError("Payload is falsy"));
  24. } else {
  25. try {
  26. const validate = ajv.compile(schema);
  27. const valid = validate(payload);
  28. if (valid && !validate.errors) {
  29. resolve(_.cloneDeep(payload));
  30. } else {
  31. const message = ajv.errorsText(validate.errors);
  32. reject(new errs.InternalValidationError(message));
  33. }
  34. } catch (err) {
  35. reject(err);
  36. }
  37. }
  38. });
  39. };
  40. export default validator;