diff --git a/src/hooks.ts b/src/hooks.ts index 9d217b3f..344e62a2 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 5769e115..4c4c7f14 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); };