-
-
Notifications
You must be signed in to change notification settings - Fork 146
/
vest.ts
51 lines (45 loc) 路 1.4 KB
/
vest.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
43
44
45
46
47
48
49
50
51
import { toNestError, validateFieldsNatively } from '@hookform/resolvers';
import { FieldError } from 'react-hook-form';
import promisify from 'vest/promisify';
import type { VestErrors, Resolver } from './types';
const parseErrorSchema = (
vestError: VestErrors,
validateAllFieldCriteria: boolean,
) => {
const errors: Record<string, FieldError> = {};
for (const path in vestError) {
if (!errors[path]) {
errors[path] = { message: vestError[path][0], type: '' };
}
if (validateAllFieldCriteria) {
errors[path].types = vestError[path].reduce<Record<number, string>>(
(acc, message, index) => (acc[index] = message) && acc,
{},
);
}
}
return errors;
};
export const vestResolver: Resolver =
(schema, _, resolverOptions = {}) =>
async (values, context, options) => {
const result =
resolverOptions.mode === 'sync'
? schema(values, options.names, context)
: await promisify(schema)(values, options.names, context);
if (result.hasErrors()) {
return {
values: {},
errors: toNestError(
parseErrorSchema(
result.getErrors(),
!options.shouldUseNativeValidation &&
options.criteriaMode === 'all',
),
options,
),
};
}
options.shouldUseNativeValidation && validateFieldsNatively({}, options);
return { values, errors: {} };
};