all files / src/ asyncValidation.js

100% Statements 24/24
100% Branches 10/10
100% Functions 4/4
100% Lines 18/18
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25   11× 11× 11×   20× 10×     10×        
import isPromise from 'is-promise';
import isValid from './isValid';
 
const asyncValidation = (fn, start, stop, field) => {
  start(field);
  const promise = fn();
  if (!isPromise(promise)) {
    throw new Error('asyncValidate function passed to reduxForm must return a promise');
  }
  const handleErrors = rejected => errors => {
    if (!isValid(errors)) {
      stop(errors);
      return Promise.reject();
    } else if (rejected) {
      stop();
      throw new Error('Asynchronous validation promise was rejected without errors.');
    }
    stop();
    return Promise.resolve();
  };
  return promise.then(handleErrors(false), handleErrors(true));
};
 
export default asyncValidation;