mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-13 23:14:53 +09:00
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:
1 parent
a5c7eb3a27
commit
ae542e9501
2 files changed
+27
-7
No files matched your search
@@ -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;
|
||||
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
Reference in new issue
Block a user