mirror of
https://github.com/profullstack/logicsrc.git
synced 2026-08-15 07:17:30 +00:00
perf(validators): cache compiled AJV validators instead of recompiling each call
validate() was creating a new AJV instance and recompiling the schema on every invocation. Schema compilation is expensive (JSON Schema parsing, format setup). Cache the compiled validator per SchemaKind so compilation happens once.
This commit is contained in:
parent
8f4691584c
commit
07e93ce9ff
1 changed files with 11 additions and 2 deletions
|
|
@ -17,6 +17,16 @@ export function createValidator() {
|
|||
return ajv;
|
||||
}
|
||||
|
||||
const _ajv = createValidator();
|
||||
const _compiledValidators = new Map<SchemaKind, ReturnType<typeof _ajv.compile>>();
|
||||
|
||||
function getCompiledValidator(kind: SchemaKind) {
|
||||
if (!_compiledValidators.has(kind)) {
|
||||
_compiledValidators.set(kind, _ajv.compile(schemas[kind]));
|
||||
}
|
||||
return _compiledValidators.get(kind)!;
|
||||
}
|
||||
|
||||
export function parseDocument(input: string, fileName = "document") {
|
||||
if (fileName.endsWith(".json")) {
|
||||
return JSON.parse(input) as unknown;
|
||||
|
|
@ -26,8 +36,7 @@ export function parseDocument(input: string, fileName = "document") {
|
|||
}
|
||||
|
||||
export function validate(kind: SchemaKind, data: unknown): ValidationResult {
|
||||
const ajv = createValidator();
|
||||
const validateDocument = ajv.compile(schemas[kind]);
|
||||
const validateDocument = getCompiledValidator(kind);
|
||||
const ok = validateDocument(data);
|
||||
|
||||
if (ok) {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue