-
-
Notifications
You must be signed in to change notification settings - Fork 144
/
class-validator.ts
56 lines (48 loc) 路 1.49 KB
/
class-validator.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
import { FieldErrors } from 'react-hook-form';
import { toNestError } from '@hookform/resolvers';
import { plainToClass } from 'class-transformer';
import { validate, validateSync, ValidationError } from 'class-validator';
import type { Resolver } from './types';
const parseErrors = (
errors: ValidationError[],
validateAllFieldCriteria: boolean,
parsedErrors: FieldErrors = {},
path = '',
) => {
return errors.reduce((acc, error) => {
const _path = path ? `${path}.${error.property}` : error.property;
if (error.constraints) {
const key = Object.keys(error.constraints)[0];
acc[_path] = {
type: key,
message: error.constraints[key],
};
if (validateAllFieldCriteria && acc[_path]) {
Object.assign(acc[_path], { types: error.constraints });
}
}
if (error.children && error.children.length) {
parseErrors(error.children, validateAllFieldCriteria, acc, _path);
}
return acc;
}, parsedErrors);
};
export const classValidatorResolver: Resolver = (
schema,
schemaOptions = {},
resolverOptions = {},
) => async (values, _, options) => {
const user = plainToClass(schema, values);
const rawErrors = await (resolverOptions.mode === 'sync'
? validateSync
: validate)(user, schemaOptions);
return rawErrors.length
? {
values: {},
errors: toNestError(
parseErrors(rawErrors, options.criteriaMode === 'all'),
options.fields,
),
}
: { values, errors: {} };
};