Refactored json-schema to use one instance of ajv (#10746)

refs https://github.com/TryGhost/Team/issues/211

Previous code was creating a new ajv instance for each call, as well as
loading the schemas, which are cached. This was causing a memory leak as
ajv caches all schemas.

We've replaced it with one instance of ajv, and conditionally
loading/compiling the schemas if they haven't been seen before.
This commit is contained in:
Fabien O'Carroll 2019-05-15 13:28:10 +02:00 committed by GitHub
parent 5b0b7e4d8d
commit 53b884ec2b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -3,15 +3,22 @@ const Ajv = require('ajv');
const stripKeyword = require('./strip-keyword');
const common = require('../../../../../lib/common');
const validate = (schema, definitions, data) => {
const ajv = new Ajv({
allErrors: true,
useDefaults: true
});
const ajv = new Ajv({
allErrors: true,
useDefaults: true
});
stripKeyword(ajv);
stripKeyword(ajv);
const validation = ajv.addSchema(definitions).compile(schema);
const getValidation = (schema, def) => {
if (!ajv.getSchema(def.$id)) {
ajv.addSchema(def);
}
return ajv.getSchema(schema.$id) || ajv.compile(schema);
};
const validate = (schema, definition, data) => {
const validation = getValidation(schema, definition);
validation(data);