custom-validation.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.CustomValidation = void 0;
  4. class CustomValidation {
  5. constructor(validator, negated) {
  6. this.validator = validator;
  7. this.negated = negated;
  8. }
  9. async run(context, value, meta) {
  10. try {
  11. const result = this.validator(value, meta);
  12. const actualResult = await result;
  13. const isPromise = result?.then;
  14. const failed = this.negated ? actualResult : !actualResult;
  15. // A promise that was resolved only adds an error if negated.
  16. // Otherwise it always succeeds
  17. if ((!isPromise && failed) || (isPromise && this.negated)) {
  18. context.addError({ type: 'field', message: this.message, value, meta });
  19. }
  20. }
  21. catch (err) {
  22. if (this.negated) {
  23. return;
  24. }
  25. context.addError({
  26. type: 'field',
  27. message: this.message || (err instanceof Error ? err.message : err),
  28. value,
  29. meta,
  30. });
  31. }
  32. }
  33. }
  34. exports.CustomValidation = CustomValidation;