All files / src/helpers initializationUtils.js

100% Statements 30/30
100% Branches 15/15
100% Functions 7/7
100% Lines 29/29

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 76 77 78 79 80 81 82 83 84 85 86 87                  23x 11x 12x 1x   11x               124x       124x 20x   124x               20x 10x 10x   1x     20x       20x   20x           20x 10x   10x       7x       7x 13x 12x     7x 7x 13x 2x             7x   7x    
import is from 'is_js';
import {FieldStatus} from "./helpers";
import {checkIsFormOK, rulesRunner} from "./validationUtils";
 
/**
 * Create initial value for a field if no default is provided.
 *
 */
export function createInitialValue(schema) {
  if (is.propertyDefined(schema, 'default')) {
    return schema.default;
  } else if (is.propertyDefined(schema, 'min')) {
    return schema.min;
  }
  return '';
}
 
/**
 * Create a new state for a field in componentState.formStatus.fields.field
 *
 */
export function createNewFieldState(needValue = false, fieldSchema) {
  const result = {
    status: FieldStatus.normal,
    errorText: ''
  };
  if (needValue) {
    result.value = createInitialValue(fieldSchema);
  }
  return result;
}
 
/**
 * When the schema contains a default rule
 */
function validateStateIfHasDefaultValue(schema, fieldName, fieldValue) {
  let result;
  if (is.propertyDefined(schema[fieldName], 'default')){
    try {
      result = rulesRunner(fieldValue, schema)
    } catch (err) {
      result = err
    }
  }
  return result;
}
 
export function createFieldState(schema, fieldName){
  const initialFieldState = createNewFieldState(true, schema[fieldName]);
 
  const result = validateStateIfHasDefaultValue(
    schema,
    fieldName,
    initialFieldState.value
  );
 
  if (result) {
    return result;
  }
  return initialFieldState;
}
 
export function createInitialState(schema, userState) {
  const initialState = {
    ...userState
  };
 
  Object.keys(schema).forEach(fieldName => {
    if (fieldName === 'collectValues') return;
    initialState[fieldName] = createFieldState(schema, fieldName);
  });
 
  const schemaItems = Object.keys(schema);
  schemaItems.forEach(name => {
    if (is.propertyDefined(userState, name)) {
      initialState[name] = {
        ...initialState[name],
        ...userState[name]
      };
    }
  });
 
  checkIsFormOK(schema, initialState);
 
  return initialState;
}