Skip to content

Commit 7a3286f

Browse files
committed
Patch validator must keep required with discriminator
1 parent 8f88965 commit 7a3286f

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

‎lib/model/AjvValidator.js‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -253,8 +253,12 @@ function objectHasDefaults(obj) {
253253

254254
function jsonSchemaWithoutRequired(jsonSchema) {
255255
const subSchemaProps = ['anyOf', 'oneOf', 'allOf', 'not', 'then', 'else'];
256+
const omitProps = subSchemaProps.slice();
257+
if (!jsonSchema.discriminator) {
258+
omitProps.push('required');
259+
}
256260
return Object.assign(
257-
omit(jsonSchema, ['required', ...subSchemaProps]),
261+
omit(jsonSchema, omitProps),
258262
...subSchemaProps.map((prop) => subSchemaWithoutRequired(jsonSchema, prop)),
259263
jsonSchema && jsonSchema.definitions
260264
? {

‎tests/unit/model/AjvValidator.js‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,28 @@ describe('AjvValidator', () => {
3434
anyOf: [{ $ref: '#/definitions/TestRef1' }, { $ref: '#/definitions/TestRef2' }],
3535
};
3636

37+
const schema2 = {
38+
type: 'object',
39+
discriminator: { propertyName: 'foo' },
40+
required: ['foo'],
41+
oneOf: [
42+
{
43+
properties: {
44+
foo: { const: 'x' },
45+
a: { type: 'string' },
46+
},
47+
required: ['a'],
48+
},
49+
{
50+
properties: {
51+
foo: { enum: ['y', 'z'] },
52+
b: { type: 'string' },
53+
},
54+
required: ['b'],
55+
},
56+
],
57+
};
58+
3759
it('should remove required fields from definitions', () => {
3860
const validator = new AjvValidator({ onCreateAjv: () => {} });
3961
const validators = validator.getValidator(modelClass('test', schema), schema, true);
@@ -42,5 +64,16 @@ describe('AjvValidator', () => {
4264
expect(definitions.length).to.be(2);
4365
definitions.forEach((d) => expect(d.required).to.be(undefined));
4466
});
67+
68+
it('should not remove required fields if there is a discriminator', () => {
69+
const validator = new AjvValidator({
70+
onCreateAjv: () => {},
71+
options: {
72+
discriminator: true,
73+
},
74+
});
75+
const validators = validator.getValidator(modelClass('test', schema2), schema2, true);
76+
expect(validators.schema.required).to.be(schema2.required);
77+
});
4578
});
4679
});

0 commit comments

Comments
 (0)