Lazy compile schema validators for ctl

Speed up the startup time for ctl by delaying schemas compilation until
the validator is used. Saves approximately 120ms on startup time.
This commit is contained in:
Hornwitser committed 2023-07-28 21:36:43 +02:00
1 parent a5c7eb3a27
commit ae542e9501
2 files changed
+27 -7

No files matched your search

+2
View File
@@ -10,6 +10,8 @@ const yargs = require("yargs");
const version = require("./package").version;
const setBlocking = require("set-blocking");
// Reduce startup time by lazy compiling schemas.
global.lazySchemaCompilation = true;
const lib = require("@clusterio/lib");
const { ConsoleTransport, levels, logger } = lib;
+25 -7
View File
@@ -5,18 +5,36 @@
"use strict";
const Ajv = require("ajv");
const ajv = new Ajv({
// These are duplicated in scripts/compile_validator
allowUnionTypes: true,
strict: "log",
strictTuples: false,
verbose: true,
});
/**
* Compile JSON schema into validator
* @function
* @param {Object} schema - JSON schema to create validator for.
* @returns {Function} Validator for the schema.
*/
function compile(schema) {
if (typeof global !== "object" || !global.lazySchemaCompilation) {
return ajv.compile(schema);
}
let doValidate;
function validate(data) {
if (!doValidate) {
doValidate = ajv.compile(schema);
}
let result = doValidate(data);
validate.errors = doValidate.errors;
return result;
}
return validate;
}
module.exports = {
/**
* Compile JSON schema into validator
* @function
* @param {Object} schema - JSON schema to create validator for.
* @returns {Function} Validator for the schema.
*/
compile: ajv.compile.bind(ajv),
compile,
};