From a4c0f393e6bee7585d8203a5478bda06f77c742a Mon Sep 17 00:00:00 2001 From: Matthias Schwarz <70815012+matthiasschwarz@users.noreply.github.com> Date: Mon, 9 Sep 2024 20:47:33 +0200 Subject: [PATCH] perf(ajv): reuse compiled schema --- README.md | 6 +++--- ajv/src/ajv.ts | 44 ++++++++++++++++++++++++-------------------- 2 files changed, 27 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index 07a0362f..de9a9b0e 100644 --- a/README.md +++ b/README.md @@ -465,14 +465,14 @@ const schema = { additionalProperties: false, }; +const resolver = ajvResolver(schema); + const App = () => { const { register, handleSubmit, formState: { errors }, - } = useForm({ - resolver: ajvResolver(schema), - }); + } = useForm({ resolver }); return (
console.log(data))}> diff --git a/ajv/src/ajv.ts b/ajv/src/ajv.ts index 19146a13..62f67bfd 100644 --- a/ajv/src/ajv.ts +++ b/ajv/src/ajv.ts @@ -45,28 +45,31 @@ const parseErrorSchema = ( }, {}); }; -export const ajvResolver: Resolver = - (schema, schemaOptions, resolverOptions = {}) => - async (values, _, options) => { - const ajv = new Ajv( - Object.assign( - {}, - { - allErrors: true, - validateSchema: true, - }, - schemaOptions, - ), - ); +export const ajvResolver: Resolver = ( + schema, + schemaOptions, + resolverOptions = {}, +) => { + const ajv = new Ajv( + Object.assign( + {}, + { + allErrors: true, + validateSchema: true, + }, + schemaOptions, + ), + ); + + ajvErrors(ajv); - ajvErrors(ajv); + const modifiedSchema = Object.assign( + { $async: resolverOptions && resolverOptions.mode === 'async' }, + schema, + ); - const validate = ajv.compile( - Object.assign( - { $async: resolverOptions && resolverOptions.mode === 'async' }, - schema, - ), - ); + return async (values, _, options) => { + const validate = ajv.compile(modifiedSchema); const valid = validate(values); @@ -86,3 +89,4 @@ export const ajvResolver: Resolver = ), }; }; +};