Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refact: memoize ajv instance for given schema #441

Merged
merged 1 commit into from
Sep 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 14 additions & 9 deletions src/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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],
);
};

Expand All @@ -104,5 +109,5 @@ export const useDatsValidator = () => {
const datsSchema = {
type: "object",
};
return useJsonSchemaValidator(datsSchema, false);
return useJsonSchemaValidator(datsSchema, "dats", false);
};
2 changes: 1 addition & 1 deletion src/modules/metadata/hooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,5 +69,5 @@ export const useDiscoverySchema = () => {

export const useDiscoveryValidator = () => {
const discoverySchema = useDiscoverySchema();
return useJsonSchemaValidator(discoverySchema, true);
return useJsonSchemaValidator(discoverySchema, "discovery", true);
};