-
-
Notifications
You must be signed in to change notification settings - Fork 145
/
joi.ts
76 lines (73 loc) 路 1.89 KB
/
joi.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
71
72
73
74
75
76
import {
appendErrors,
transformToNestObject,
Resolver,
FieldValues,
} from 'react-hook-form';
import * as Joi from 'joi';
import convertArrayToPathName from './utils/convertArrayToPathName';
const parseErrorSchema = (
error: Joi.ValidationError,
validateAllFieldCriteria: boolean,
) =>
Array.isArray(error.details)
? error.details.reduce(
(previous: Record<string, any>, { path, message = '', 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 joiResolver = <TFieldValues extends FieldValues>(
schema: Joi.Schema,
options: Joi.AsyncValidationOptions = {
abortEarly: false,
},
): Resolver<TFieldValues> => async (
values,
context,
validateAllFieldCriteria = false,
) => {
try {
return {
values: await schema.validateAsync(values, {
...options,
context,
}),
errors: {},
};
} catch (e) {
return {
values: {},
errors: transformToNestObject(
parseErrorSchema(e, validateAllFieldCriteria),
),
};
}
};