api.js 928 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import Ajv from "ajv/dist/2020.js";
  2. import errs from "../error.js";
  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. const apiValidator = async (schema, payload /*, description*/) => {
  16. if (!schema) {
  17. throw new errs.ValidationError("Schema is undefined");
  18. }
  19. // Can't use falsy check here as valid payload could be `0` or `false`
  20. if (typeof payload === "undefined") {
  21. throw new errs.ValidationError("Payload is undefined");
  22. }
  23. const validate = ajv.compile(schema);
  24. const valid = validate(payload);
  25. if (valid && !validate.errors) {
  26. return payload;
  27. }
  28. const message = ajv.errorsText(validate.errors);
  29. const err = new errs.ValidationError(message);
  30. err.debug = {validationErrors: validate.errors, payload};
  31. throw err;
  32. };
  33. export default apiValidator;