Skip to content

Commit

Permalink
Upgrade Valibot and refactor resolver with new util
Browse files Browse the repository at this point in the history
  • Loading branch information
fabian-hiller committed Jun 4, 2024
1 parent 67d778c commit 3b2e265
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 46 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,7 @@
"superstruct": "^1.0.3",
"typanion": "^3.14.0",
"typescript": "^5.1.6",
"valibot": "0.31.0-rc.11",
"valibot": "0.31.0-rc.12",
"vest": "^4.6.11",
"vite": "^4.4.9",
"vite-tsconfig-paths": "^4.2.0",
Expand Down
10 changes: 5 additions & 5 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

64 changes: 24 additions & 40 deletions valibot/src/valibot.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { toNestErrors } from '@hookform/resolvers';
import { FieldError, appendErrors, FieldValues } from 'react-hook-form';
import { safeParseAsync } from 'valibot';
import { getDotPath, safeParseAsync } from 'valibot';
import type { Resolver } from './types';

export const valibotResolver: Resolver =
Expand All @@ -23,47 +23,31 @@ export const valibotResolver: Resolver =

// Iterate over issues to add them to errors object
for (const issue of result.issues) {
if (issue.path) {
// Create path string from issue path
let path = '';
for (const item of issue.path) {
if (
'key' in item &&
(typeof item.key === 'string' || typeof item.key === 'number')
) {
if (path) {
path += `.${item.key}`;
} else {
path += item.key;
}
} else {
break;
}
}
// Create dot path from issue
const path = getDotPath(issue);

if (path) {
// Add first error of path to errors object
if (!errors[path]) {
errors[path] = { message: issue.message, type: issue.type };
}
if (path) {
// Add first error of path to errors object
if (!errors[path]) {
errors[path] = { message: issue.message, type: issue.type };
}

// If configured, add all errors of path to errors object
if (validateAllFieldCriteria) {
const types = errors[path].types;
const messages = types && types[issue.type];
errors[path] = appendErrors(
path,
validateAllFieldCriteria,
errors,
issue.type,
messages
? ([] as string[]).concat(
messages as string | string[],
issue.message,
)
: issue.message,
) as FieldError;
}
// If configured, add all errors of path to errors object
if (validateAllFieldCriteria) {
const types = errors[path].types;
const messages = types && types[issue.type];
errors[path] = appendErrors(
path,
validateAllFieldCriteria,
errors,
issue.type,
messages
? ([] as string[]).concat(
messages as string | string[],
issue.message,
)
: issue.message,
) as FieldError;
}
}
}
Expand Down

0 comments on commit 3b2e265

Please sign in to comment.