From 3141856ceed034d68c1c21247e5f9f86e5014246 Mon Sep 17 00:00:00 2001 From: v-rocheleau Date: Tue, 10 Sep 2024 18:58:02 +0000 Subject: [PATCH] refact: memoize ajv instance for given schema --- src/hooks.ts | 23 ++++++++++++++--------- src/modules/metadata/hooks.js | 2 +- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/src/hooks.ts b/src/hooks.ts index 9d217b3fd..344e62a25 100644 --- a/src/hooks.ts +++ b/src/hooks.ts @@ -75,26 +75,31 @@ export const useOpenIDConfigNotLoaded = (): boolean => { return openIdConfigHasAttempted === false || openIdConfigFetching; }; -export const useJsonSchemaValidator = (schema: SchemaObject, acceptFalsyValue: boolean) => { - const ajv = useMemo(() => new Ajv(), []); +export const useJsonSchemaValidator = (schema: SchemaObject, schemaName: string, acceptFalsyValue: boolean) => { + const ajv = useMemo(() => { + if (schema) { + // for schemas obtained by API: only instantiate Ajv when the schema is resolved + return new Ajv().addSchema(schema, schemaName); + } + }, [schema, schemaName]); return useCallback( (rule: unknown, value: unknown) => { - if (!schema) { - return Promise.reject(new Error("No JSON schema provided, cannot validate.")); + const validator = ajv?.getSchema(schemaName); + if (!ajv || !validator) { + return Promise.reject(new Error(`No JSON schema provided for ${schemaName}, cannot validate.`)); } if (!value && acceptFalsyValue) { return Promise.resolve(); } - const valid = ajv.validate(schema, value); - if (valid) { + if (validator(value)) { return Promise.resolve(); } else { - return Promise.reject(new Error(ajv.errorsText(ajv.errors))); + return Promise.reject(new Error(ajv.errorsText(validator.errors))); } }, - [acceptFalsyValue, ajv, schema], + [acceptFalsyValue, ajv, schemaName], ); }; @@ -104,5 +109,5 @@ export const useDatsValidator = () => { const datsSchema = { type: "object", }; - return useJsonSchemaValidator(datsSchema, false); + return useJsonSchemaValidator(datsSchema, "dats", false); }; diff --git a/src/modules/metadata/hooks.js b/src/modules/metadata/hooks.js index 5769e115c..4c4c7f140 100644 --- a/src/modules/metadata/hooks.js +++ b/src/modules/metadata/hooks.js @@ -69,5 +69,5 @@ export const useDiscoverySchema = () => { export const useDiscoveryValidator = () => { const discoverySchema = useDiscoverySchema(); - return useJsonSchemaValidator(discoverySchema, true); + return useJsonSchemaValidator(discoverySchema, "discovery", true); };