All files / src/functions/setFormErrors index.ts

100% Statements 32/32
100% Branches 12/12
100% Functions 1/1
100% Lines 19/19

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        1x                 1x 2x   2x 6x 6x   6x 2x     4x       4x 1x 3x   3x   3x     3x     3x     1x       3x       2x    
import { FormErrors } from './types';
import { Form } from '../../components/FormBuilder/types';
import { FieldOptions } from '../../components/FormField/types';
 
import { deepCopy } from '@cnamts/vue-dot/src/helpers/deepCopy';
 
/**
 * Set error-messages prop on the fields in error
 *
 * @param {FormErrors} formErrors The errors list for each fields from the api
 * @param {Form} form The form to modify
 * @returns {Form} The form modified with errorsMessages
 */
export function setFormErrors(formErrors: FormErrors, form: Form): Form {
	const newForm = deepCopy<Form>(form);
 
	for (const [sectionName] of Object.entries(newForm)) {
		for (const [fieldName, errors] of Object.entries(formErrors)) {
			const field = newForm[sectionName].questions[fieldName];
 
			if (!field || !errors) {
				continue;
			}
 
			const fieldOptions = field.fieldOptions || {};
 
			// If the field exists in our form and we
			// have errors to set, set errors
			if (Array.isArray(errors)) {
				(fieldOptions as FieldOptions).errorMessages = errors;
			} else if (typeof errors === 'object') {
				// For each sub field in error
				for (const [subFieldName, subErrors] of Object.entries(errors)) {
					// Get the sub field fieldOptions or create it
					const subFieldOptions = fieldOptions[subFieldName] || {};
 
					// Add error messages to the sub field fieldOptions
					(subFieldOptions as FieldOptions).errorMessages = subErrors;
 
					// Update the field fieldOptions
					fieldOptions[subFieldName] = subFieldOptions;
				}
			} else {
				continue;
			}
 
			// Set the new field fieldOptions to the form
			newForm[sectionName].questions[fieldName].fieldOptions = fieldOptions;
		}
	}
 
	return newForm;
}