From 4309d1c071792e4efec51d1509f41a8709965b0e Mon Sep 17 00:00:00 2001 From: Joris Date: Wed, 4 Aug 2021 09:59:59 +0200 Subject: [PATCH] perf(typanion): reduce bundle size (#192) --- typanion/src/typanion.ts | 44 ++++++++++++++++++++++------------------ 1 file changed, 24 insertions(+), 20 deletions(-) diff --git a/typanion/src/typanion.ts b/typanion/src/typanion.ts index 5ff352c5..221eca8e 100644 --- a/typanion/src/typanion.ts +++ b/typanion/src/typanion.ts @@ -2,18 +2,12 @@ import type { FieldErrors } from 'react-hook-form'; import { toNestError, validateFieldsNatively } from '@hookform/resolvers'; import type { Resolver } from './types'; -const parseErrors = ( - errors: string[], - parsedErrors: FieldErrors = {}, - _path = '', -) => { +const parseErrors = (errors: string[], parsedErrors: FieldErrors = {}) => { return errors.reduce((acc, error) => { - const [_key, _message] = error.split(':') - const key = _key.slice(1) - const message = _message.trim() + const e = error.split(':'); - acc[key] = { - message, + acc[e[0].slice(1)] = { + message: e[1].trim(), }; return acc; @@ -22,16 +16,26 @@ const parseErrors = ( export const typanionResolver: Resolver = (validator, validatorOptions = {}) => - (values, _, options) => { - const rawErrors: string[] = [] - const isValid = validator(values, {errors: rawErrors, ...validatorOptions}) - const parsedErrors = parseErrors(rawErrors) + (values, _, options) => { + const rawErrors: string[] = []; + const isValid = validator( + values, + Object.assign( + {}, + { + errors: rawErrors, + }, + validatorOptions, + ), + ); + const parsedErrors = parseErrors(rawErrors); - if (!isValid) { - return { values: {}, errors: toNestError(parsedErrors, options) }; - } - - options.shouldUseNativeValidation && validateFieldsNatively(parsedErrors, options); + if (isValid) { + options.shouldUseNativeValidation && + validateFieldsNatively(parsedErrors, options); return { values, errors: {} }; - }; \ No newline at end of file + } + + return { values: {}, errors: toNestError(parsedErrors, options) }; + };