api.js 1009 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. const Ajv = require('ajv/dist/2020');
  2. const error = require('../error');
  3. const ajv = new Ajv({
  4. verbose: true,
  5. allErrors: true,
  6. allowUnionTypes: true,
  7. strict: false,
  8. coerceTypes: true,
  9. });
  10. /**
  11. * @param {Object} schema
  12. * @param {Object} payload
  13. * @returns {Promise}
  14. */
  15. function apiValidator (schema, payload/*, description*/) {
  16. return new Promise(function Promise_apiValidator (resolve, reject) {
  17. if (schema === null) {
  18. reject(new error.ValidationError('Schema is undefined'));
  19. return;
  20. }
  21. if (typeof payload === 'undefined') {
  22. reject(new error.ValidationError('Payload is undefined'));
  23. return;
  24. }
  25. const validate = ajv.compile(schema);
  26. const valid = validate(payload);
  27. if (valid && !validate.errors) {
  28. resolve(payload);
  29. } else {
  30. let message = ajv.errorsText(validate.errors);
  31. let err = new error.ValidationError(message);
  32. err.debug = [validate.errors, payload];
  33. reject(err);
  34. }
  35. });
  36. }
  37. module.exports = apiValidator;