-
-
Notifications
You must be signed in to change notification settings - Fork 146
/
computed-types.ts
42 lines (35 loc) 路 1.13 KB
/
computed-types.ts
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
import type { FieldErrors } from 'react-hook-form';
import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';
import type { Resolver } from './types';
import type { ValidationError } from 'computed-types';
const isValidationError = (error: any): error is ValidationError =>
error.errors != null;
const parseErrorSchema = (computedTypesError: ValidationError) => {
const parsedErrors: FieldErrors = {};
return (computedTypesError.errors || []).reduce((acc, error) => {
acc[error.path.join('.')] = {
type: error.error.name,
message: error.error.message,
};
return acc;
}, parsedErrors);
};
export const computedTypesResolver: Resolver =
(schema) => async (values, _, options) => {
try {
const data = await schema(values);
options.shouldUseNativeValidation && validateFieldsNatively({}, options);
return {
errors: {},
values: data,
};
} catch (error: any) {
if (isValidationError(error)) {
return {
values: {},
errors: toNestErrors(parseErrorSchema(error), options),
};
}
throw error;
}
};