Skip to content

Commit

Permalink
feat: provide zodResolverSync
Browse files Browse the repository at this point in the history
  • Loading branch information
kotarella1110 committed Oct 19, 2023
1 parent 4682803 commit 88dc51e
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 1 deletion.
20 changes: 20 additions & 0 deletions zod/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,23 @@ export type Resolver = <T extends z.Schema<any, any>>(
context: TContext | undefined,
options: ResolverOptions<TFieldValues>,
) => Promise<ResolverResult<TFieldValues>>;

export type ResolverSync = <T extends z.Schema<any, any>>(
schema: T,
schemaOptions?: Partial<z.ParseParams>,
factoryOptions?: {
/**
* @default async
*/
mode?: 'async' | 'sync';
/**
* Return the raw input values rather than the parsed values.
* @default false
*/
raw?: boolean;
},
) => <TFieldValues extends FieldValues, TContext>(
values: TFieldValues,
context: TContext | undefined,
options: ResolverOptions<TFieldValues>,
) => ResolverResult<TFieldValues>;
33 changes: 32 additions & 1 deletion zod/src/zod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { appendErrors } from 'react-hook-form/logic';
import type { FieldError, FieldErrors } from 'react-hook-form';
import { z, ZodError } from 'zod';
import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';
import type { Resolver } from './types';
import type { Resolver, ResolverSync } from './types';

const isZodError = (error: any): error is ZodError => error.errors != null;

Expand Down Expand Up @@ -88,3 +88,34 @@ export const zodResolver: Resolver =
throw error;
}
};

export const zodResolverSync: ResolverSync =
(schema, schemaOptions, resolverOptions = {}) =>
(values, _, options) => {
try {
const data = schema.parse(values, schemaOptions);

options.shouldUseNativeValidation && validateFieldsNatively({}, options);

return {
errors: {} as FieldErrors,
values: resolverOptions.raw ? values : data,
};
} catch (error: any) {
if (isZodError(error)) {
return {
values: {},
errors: toNestErrors(
parseErrorSchema(
error.errors,
!options.shouldUseNativeValidation &&
options.criteriaMode === 'all',
),
options,
),
};
}

throw error;
}
};

0 comments on commit 88dc51e

Please sign in to comment.