diff --git a/lib/model/AjvValidator.js b/lib/model/AjvValidator.js index 723b37217..2f0e10368 100644 --- a/lib/model/AjvValidator.js +++ b/lib/model/AjvValidator.js @@ -1,17 +1,11 @@ 'use strict'; +const Ajv = require('ajv'); +const addFormats = require('ajv-formats'); const { Validator } = require('./Validator'); const { ValidationErrorType } = require('../model/ValidationError'); const { isObject, once, cloneDeep: lodashCloneDeep, omit } = require('../utils/objectUtils'); -const getAjv = once(() => { - try { - return require('ajv'); - } catch (err) { - throw new Error('Optional ajv dependency not installed. Please run `npm install ajv --save`'); - } -}); - class AjvValidator extends Validator { static init(self, conf) { super.init(self, conf); @@ -20,8 +14,6 @@ class AjvValidator extends Validator { allErrors: true, }); - const Ajv = getAjv(); - // Create a normal Ajv instance. self.ajv = new Ajv( Object.assign( @@ -43,8 +35,13 @@ class AjvValidator extends Validator { // A cache for the compiled validator functions. self.cache = new Map(); - conf.onCreateAjv(self.ajv); - conf.onCreateAjv(self.ajvNoDefaults); + const setupAjv = (ajv) => { + addFormats(ajv); + conf.onCreateAjv(ajv); + }; + + setupAjv(self.ajv); + setupAjv(self.ajvNoDefaults); } beforeValidate({ json, model, options, ctx }) { diff --git a/package-lock.json b/package-lock.json index 00878a3b5..03cb6bbe7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,6 +10,7 @@ "license": "MIT", "dependencies": { "ajv": "^8.6.2", + "ajv-formats": "^2.1.1", "db-errors": "^0.2.3" }, "devDependencies": { @@ -3670,6 +3671,22 @@ "ajv": ">=5.0.0" } }, + "node_modules/ajv-formats": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-2.1.1.tgz", + "integrity": "sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, "node_modules/algoliasearch": { "version": "3.35.1", "resolved": "https://registry.npmjs.org/algoliasearch/-/algoliasearch-3.35.1.tgz", @@ -22166,6 +22183,14 @@ "dev": true, "requires": {} }, + "ajv-formats": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-2.1.1.tgz", + "integrity": "sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==", + "requires": { + "ajv": "^8.0.0" + } + }, "algoliasearch": { "version": "3.35.1", "resolved": "https://registry.npmjs.org/algoliasearch/-/algoliasearch-3.35.1.tgz", diff --git a/package.json b/package.json index d784ad538..43c36ef15 100644 --- a/package.json +++ b/package.json @@ -54,6 +54,7 @@ "types": "./typings/objection/index.d.ts", "dependencies": { "ajv": "^8.6.2", + "ajv-formats": "^2.1.1", "db-errors": "^0.2.3" }, "peerDependencies": {