all files / src/ setErrors.js

96.55% Statements 56/58
92.31% Branches 48/52
100% Functions 10/10
94.59% Lines 35/37
6 statements, 1 function, 3 branches Ignored     
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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75   271×         207× 100×   99× 59× 226×           59× 14×   59×   40×   207×     207× 68×     68×   60×   139× 77×         62× 15× 12× 14×       47×         41× 41×   45×                  
import {isFieldValue, makeFieldValue} from './fieldValue';
 
const isMetaKey = key => key[0] === '_';
 
/**
 * Sets an error on a field deep in the tree, returning a new copy of the state
 */
const setErrors = (state, errors, destKey) => {
  const clear = () => {
    if (Array.isArray(state)) {
      return state.map((stateItem, index) => setErrors(stateItem, errors && errors[index], destKey));
    }
    if (state && typeof state === 'object') {
      const result = Object.keys(state)
        .reduce((accumulator, key) =>
            isMetaKey(key) ? accumulator : {
              ...accumulator,
              [key]: setErrors(state[key], errors && errors[key], destKey)
            },
          state);
      if (isFieldValue(state)) {
        makeFieldValue(result);
      }
      return result;
    }
    return makeFieldValue(state);
  };
  Iif (typeof File !== 'undefined' && state instanceof File) {
    return state;
  }
  if (!errors) {
    Iif (!state) {
      return state;
    }
    if (state[destKey]) {
      const copy = {...state};
      delete copy[destKey];
      return makeFieldValue(copy);
    }
    return clear();
  }
  if (typeof errors === 'string') {
    return makeFieldValue({
      ...state,
      [destKey]: errors
    });
  }
  if (Array.isArray(errors)) {
    if (!state || Array.isArray(state)) E{
      const copy = (state || []).map((stateItem, index) => setErrors(stateItem, errors[index], destKey));
      errors.forEach((errorItem, index) => copy[index] = setErrors(copy[index], errorItem, destKey));
      return copy;
    }
    return setErrors(state, errors[0], destKey);  // use first error
  }
  if (isFieldValue(state)) {
    return makeFieldValue({
      ...state,
      [destKey]: errors
    });
  }
  const errorKeys = Object.keys(errors);
  if (!errorKeys.length && !state) {
    return state;
  }
  return errorKeys.reduce((accumulator, key) =>
      isMetaKey(key) ? accumulator : {
        ...accumulator,
        [key]: setErrors(state && state[key], errors[key], destKey)
      },
    clear() || {});
};
 
export default setErrors;