File size: 2,912 Bytes
95ca844
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';
import {
  AsyncValidator,
  ValidationErrors,
  Validator,
} from 'fluentvalidation-ts';
import { FieldError, FieldValues, Resolver } from 'react-hook-form';

function traverseObject<T>(
  object: ValidationErrors<T>,
  errors: Record<string, FieldError>,
  parentIndices: (string | number)[] = [],
) {
  for (const key in object) {
    const currentIndex = [...parentIndices, key];
    const currentValue = object[key];

    if (Array.isArray(currentValue)) {
      currentValue.forEach((item: any, index: number) => {
        traverseObject(item, errors, [...currentIndex, index]);
      });
    } else if (typeof currentValue === 'object' && currentValue !== null) {
      traverseObject(currentValue, errors, currentIndex);
    } else if (typeof currentValue === 'string') {
      errors[currentIndex.join('.')] = {
        type: 'validation',
        message: currentValue,
      };
    }
  }
}

const parseErrorSchema = <T>(
  validationErrors: ValidationErrors<T>,
  validateAllFieldCriteria: boolean,
) => {
  if (validateAllFieldCriteria) {
    // TODO: check this but i think its always one validation error
  }

  const errors: Record<string, FieldError> = {};
  traverseObject(validationErrors, errors);

  return errors;
};

export function fluentValidationResolver<TFieldValues extends FieldValues>(
  validator: Validator<TFieldValues>,
): Resolver<TFieldValues> {
  return async (values, _context, options) => {
    const validationResult = validator.validate(values);
    const isValid = Object.keys(validationResult).length === 0;

    options.shouldUseNativeValidation && validateFieldsNatively({}, options);

    return isValid
      ? {
          values: values,
          errors: {},
        }
      : {
          values: {},
          errors: toNestErrors(
            parseErrorSchema(
              validationResult,
              !options.shouldUseNativeValidation &&
                options.criteriaMode === 'all',
            ),
            options,
          ),
        };
  };
}

export function fluentAsyncValidationResolver<
  TFieldValues extends FieldValues,
  TValidator extends AsyncValidator<TFieldValues>,
>(validator: TValidator): Resolver<TFieldValues> {
  return async (values, _context, options) => {
    const validationResult = await validator.validateAsync(values);
    const isValid = Object.keys(validationResult).length === 0;

    options.shouldUseNativeValidation && validateFieldsNatively({}, options);

    return isValid
      ? {
          values: values,
          errors: {},
        }
      : {
          values: {},
          errors: toNestErrors(
            parseErrorSchema(
              validationResult,
              !options.shouldUseNativeValidation &&
                options.criteriaMode === 'all',
            ),
            options,
          ),
        };
  };
}