Cache the compiled schema validators
Node · Node · intermediate · modification
Adds an in-memory memo cache to getValidator so each (schemaName, draft) pair is compiled once and reused. Repeated lookups now hit the Map instead of re-running the expensive compileSchema. Behavior is unchanged; the validators returned are identical to before, just cached.
getValidator sits on the hot path of a JSON API gateway: every inbound request looks up a validator by (schemaName, draft), and compileSchema builds it by walking the full schema graph. The same handful of pairs is requested millions of times a day.
Requirements
- getValidator(schemaName, draft) must return the validator compiled for that schema and JSON Schema draft.
- compileSchema is expensive and the same (schemaName, draft) pairs recur constantly, so memoize the result: each distinct pair must be compiled at most once.
- The memo must actually take effect: a repeat call with the same (schemaName, draft) must hit the cache and return the stored validator, never recompile.
Files touched
- src/validation/validatorCache.js
--- src/validation/validatorCache.js
const { compileSchema } = require('./compileSchema');
+
+const cache = new Map();
// Returns a validator function for the named schema at the given draft version.
// compileSchema walks the whole schema graph to build the validator (hundreds of
// microseconds), and the same (schemaName, draft) pair is requested on nearly
-// every incoming request.
+// every incoming request, so we memoize the compiled result.
function getValidator(schemaName, draft) {
- return compileSchema(schemaName, draft);
+ const key = { schemaName, draft };
+ if (cache.has(key)) {
+ return cache.get(key);
+ }
+
+ const validator = compileSchema(schemaName, draft);
+ cache.set(key, validator);
+ return validator;
}