Skip to content

Commit

Permalink
[PERF] validator: Lazy load dependencies
Browse files Browse the repository at this point in the history
- Only require modules / dependencies when needed
- Create singleton validator instance only on first usage
  • Loading branch information
matz3 committed Nov 6, 2020
1 parent b69d75e commit 609346b
Showing 1 changed file with 7 additions and 5 deletions.
12 changes: 7 additions & 5 deletions lib/validation/validator.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
const Ajv = require("ajv");
const ajvErrors = require("ajv-errors");
const path = require("path");
const {promisify} = require("util");
const readFile = promisify(require("fs").readFile);

const ValidationError = require("./ValidationError");

async function loadSchema(schemaPath) {
const filePath = schemaPath.replace("http://ui5.sap/schema/", "");
const schemaFile = await readFile(path.join(__dirname, "schema", filePath), {encoding: "utf8"});
Expand All @@ -18,11 +14,13 @@ async function loadSchema(schemaPath) {
*/
class Validator {
constructor() {
const Ajv = require("ajv");
this.ajv = new Ajv({
allErrors: true,
jsonPointers: true,
loadSchema
});
const ajvErrors = require("ajv-errors");
ajvErrors(this.ajv);
}

Expand All @@ -41,6 +39,7 @@ class Validator {
const fnValidate = await this._compileSchema();
const valid = fnValidate(config);
if (!valid) {
const ValidationError = require("./ValidationError");
throw new ValidationError({
errors: fnValidate.errors,
schema: fnValidate.schema,
Expand All @@ -51,7 +50,7 @@ class Validator {
}
}

const validator = new Validator();
let validator;

/**
* @public
Expand All @@ -77,6 +76,9 @@ module.exports = {
* @public
*/
validate: async (options) => {
if (!validator) {
validator = new Validator();
}
await validator.validate(options);
},
_Validator: Validator // For testing only
Expand Down

0 comments on commit 609346b

Please sign in to comment.