diff --git a/vest/package.json b/vest/package.json index f8a0517c..90b8a090 100644 --- a/vest/package.json +++ b/vest/package.json @@ -11,6 +11,8 @@ "types": "dist/index.d.ts", "license": "MIT", "peerDependencies": { - "react-hook-form": ">=6.6.0" + "react-hook-form": ">=6.6.0", + "@hookform/resolvers": ">=2.0.0", + "vest": ">=3.0.0" } } diff --git a/vest/src/types.ts b/vest/src/types.ts index 79a2ca69..60af411c 100644 --- a/vest/src/types.ts +++ b/vest/src/types.ts @@ -11,7 +11,7 @@ export type ICreateResult = ReturnType; export type Resolver = ( schema: ICreateResult, schemaOptions?: never, - factoryOptions?: { mode: 'async' | 'sync' }, + factoryOptions?: { mode?: 'async' | 'sync' }, ) => ( values: UnpackNestedValue, context: TContext | undefined, diff --git a/vest/src/vest.ts b/vest/src/vest.ts index 44c510e6..c717ed0c 100644 --- a/vest/src/vest.ts +++ b/vest/src/vest.ts @@ -1,57 +1,45 @@ import { toNestError } from '@hookform/resolvers'; +import { FieldError } from 'react-hook-form'; import promisify from 'vest/promisify'; -import { DraftResult, IVestResult } from 'vest/vestResult'; import type { VestErrors, Resolver } from './types'; const parseErrorSchema = ( vestError: VestErrors, validateAllFieldCriteria: boolean, ) => { - return Object.entries(vestError).reduce((prev, [key, value]) => { - return { - ...prev, - [key]: { - type: '', - message: value[0], - ...(validateAllFieldCriteria - ? { - types: value.reduce((prev, message, index) => { - return { - ...prev, - [index]: message, - }; - }, {}), - } - : {}), - }, - }; - }, {}); + const errors: Record = {}; + for (const path in vestError) { + if (!errors[path]) { + errors[path] = { message: vestError[path][0], type: '' }; + } + + if (validateAllFieldCriteria) { + errors[path].types = vestError[path].reduce>( + (acc, message, index) => (acc[index] = message) && acc, + {}, + ); + } + } + return errors; }; export const vestResolver: Resolver = ( schema, _, - { mode } = { mode: 'async' }, -) => async (values, _context, { criteriaMode, fields }) => { - let result: IVestResult | DraftResult; - if (mode === 'async') { - const validateSchema = promisify(schema); - result = await validateSchema(values); - } else { - result = schema(values); - } - - const errors = result.getErrors(); - - if (!result.hasErrors()) { - return { values, errors: {} }; - } + resolverOptions = {}, +) => async (values, _context, options) => { + const result = + resolverOptions.mode === 'sync' + ? schema(values) + : await promisify(schema)(values); - return { - values: {}, - errors: toNestError( - parseErrorSchema(errors, criteriaMode === 'all'), - fields, - ), - }; + return result.hasErrors() + ? { + values: {}, + errors: toNestError( + parseErrorSchema(result.getErrors(), options.criteriaMode === 'all'), + options.fields, + ), + } + : { values, errors: {} }; };