From 53b884ec2bdc126e98d6e7fca07a4699594fa702 Mon Sep 17 00:00:00 2001 From: Fabien O'Carroll Date: Wed, 15 May 2019 13:28:10 +0200 Subject: [PATCH] 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. --- .../v2/utils/validators/utils/json-schema.js | 21 ++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/core/server/api/v2/utils/validators/utils/json-schema.js b/core/server/api/v2/utils/validators/utils/json-schema.js index 1db3ed9e3f..b355239ddc 100644 --- a/core/server/api/v2/utils/validators/utils/json-schema.js +++ b/core/server/api/v2/utils/validators/utils/json-schema.js @@ -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);