diff --git a/packages/ctl/ctl.js b/packages/ctl/ctl.js index a699e22f..07c16fbc 100755 --- a/packages/ctl/ctl.js +++ b/packages/ctl/ctl.js @@ -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; diff --git a/packages/lib/src/schema.js b/packages/lib/src/schema.js index 65f90937..63c2f5c9 100644 --- a/packages/lib/src/schema.js +++ b/packages/lib/src/schema.js @@ -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, };