Skip to content

Commit

Permalink
perf(class-validator): reduce classValidator resolver bundle size
Browse files Browse the repository at this point in the history
  • Loading branch information
jorisre committed Apr 10, 2021
1 parent a419de2 commit c61fd8f
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 23 deletions.
4 changes: 3 additions & 1 deletion class-validator/package.json
Expand Up @@ -12,6 +12,8 @@
"license": "MIT",
"peerDependencies": {
"react-hook-form": ">=6.6.0",
"@hookform/resolvers": ">=2.0.0"
"@hookform/resolvers": ">=2.0.0",
"class-transformer": "^0.4.0",
"class-validator": "^0.12.0"
}
}
44 changes: 22 additions & 22 deletions class-validator/src/class-validator.ts
@@ -1,8 +1,8 @@
import type { Resolver } from './types';
import { plainToClass } from 'class-transformer';
import { validate, validateSync, ValidationError } from 'class-validator';
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[],
Expand All @@ -14,19 +14,19 @@ const parseErrors = (
const _path = path ? `${path}.${error.property}` : error.property;

if (error.constraints) {
const [key, message] = Object.entries(error.constraints)[0];
const key = Object.keys(error.constraints)[0];
acc[_path] = {
type: key,
message,
message: error.constraints[key],
};

if (validateAllFieldCriteria && acc[_path]) {
acc[_path] = { ...acc[_path], types: error.constraints };
Object.assign(acc[_path], { types: error.constraints });
}
}

if (error.children?.length) {
parseErrors(error.children, validateAllFieldCriteria, acc, `${_path}`);
if (error.children && error.children.length) {
parseErrors(error.children, validateAllFieldCriteria, acc, _path);
}

return acc;
Expand All @@ -39,18 +39,18 @@ export const classValidatorResolver: Resolver = (
resolverOptions = {},
) => async (values, _, options) => {
const user = plainToClass(schema, values);
const rawErrors =
resolverOptions.mode === 'sync'
? validateSync(user, schemaOptions)
: await validate(user, schemaOptions);

if (rawErrors.length === 0) {
return { values, errors: {} };
}

const errors = toNestError(
parseErrors(rawErrors, options.criteriaMode === 'all'),
options.fields,
);
return { values: {}, errors };

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: {} };
};

0 comments on commit c61fd8f

Please sign in to comment.