-
-
Notifications
You must be signed in to change notification settings - Fork 146
/
zod.ts
70 lines (65 loc) 路 1.8 KB
/
zod.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { appendErrors, transformToNestObject } from 'react-hook-form';
import * as z from 'zod';
// @ts-expect-error maybe fixed after the first publish ?
import { convertArrayToPathName } from '@hookform/resolvers';
import type { Resolver } from './types';
const parseErrorSchema = (
zodError: z.ZodError,
validateAllFieldCriteria: boolean,
) => {
if (zodError.isEmpty) {
return {};
}
return zodError.errors.reduce<Record<string, any>>(
(previous, { path, message, code: type }) => {
const currentPath = convertArrayToPathName(path);
return {
...previous,
...(path
? previous[currentPath] && validateAllFieldCriteria
? {
[currentPath]: appendErrors(
currentPath,
validateAllFieldCriteria,
previous,
type,
message,
),
}
: {
[currentPath]: previous[currentPath] || {
message,
type,
...(validateAllFieldCriteria
? {
types: { [type]: message || true },
}
: {}),
},
}
: {}),
};
},
{},
);
};
export const zodResolver: Resolver = (
schema,
schemaOptions,
{ mode } = { mode: 'async' },
) => async (values, _, validateAllFieldCriteria = false) => {
try {
const result =
mode === 'async'
? await schema.parseAsync(values, schemaOptions)
: schema.parse(values, schemaOptions);
return { values: result, errors: {} };
} catch (error) {
return {
values: {},
errors: transformToNestObject(
parseErrorSchema(error, validateAllFieldCriteria),
),
};
}
};