Skip to content

Commit

Permalink
Only add AJV formats if they weren't added already
Browse files Browse the repository at this point in the history
Caused by #2453
Closes #2481
  • Loading branch information
lehni committed Jul 22, 2023
1 parent c0e7b5c commit 7a4084e
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
5 changes: 4 additions & 1 deletion lib/model/AjvValidator.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,11 @@ class AjvValidator extends Validator {
self.cache = new Map();

const setupAjv = (ajv) => {
addFormats(ajv);
conf.onCreateAjv(ajv);
// Only add AJV formats if they weren't added in user-space already
if (!ajv.formats['date-time']) {
addFormats(ajv);
}
};

setupAjv(self.ajv);
Expand Down
28 changes: 28 additions & 0 deletions tests/unit/model/AjvValidator.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
const addFormats = require('ajv-formats');
const { AjvValidator, Model } = require('../../../');
const expect = require('expect.js');

Expand Down Expand Up @@ -61,6 +62,16 @@ describe('AjvValidator', () => {
],
};

const schema3 = {
type: 'object',
properties: {
date: {
type: 'string',
format: 'date-time',
},
},
};

it('should remove required fields from definitions', () => {
const validator = new AjvValidator({ onCreateAjv: () => {} });
const validators = validator.getValidator(modelClass('test', schema), schema, true);
Expand All @@ -81,6 +92,23 @@ describe('AjvValidator', () => {
expect(validators.schema.required).to.eql(['foo']);
});

it('should add ajv formats by default', () => {
expect(() => {
const validator = new AjvValidator({ onCreateAjv: () => {} });
validator.getValidator(modelClass('test', schema3), schema3, true);
}).to.not.throwException();
});

it('should not throw errors when adding formats in onCreateAjv hook', () => {
expect(() => {
new AjvValidator({
onCreateAjv: (ajv) => {
addFormats(ajv);
},
});
}).to.not.throwException();
});

it('should handle empty definitions', () => {
const emptyDefinitionsSchema = {
type: 'object',
Expand Down

0 comments on commit 7a4084e

Please sign in to comment.