var Ajv = require('ajv');
// Initialize AJV with useDefaults option
const ajv = new Ajv({
allErrors: true,
useDefaults: true,
strict: false,
});
// Define the modified schema
const schema = {
type: 'object',
properties: {
useInterconnect: {
type: 'boolean',
default: false,
},
interconnectId: {
type: 'string',
},
},
allOf: [
{
if: {
type: 'object',
properties: {
useInterconnect: { const: true },
},
},
then: {
required: ['interconnectId'],
},
},
],
};
// Example data
const data = {};
const validate = ajv.compile(schema);
const valid = validate(data);
console.log(data); // Log: { useInterconnect: false }
if (valid) {
console.log('Data is valid:', data);
} else {
console.log('Data is invalid:', validate.errors);
}
/* Output:
Data is invalid: [
{
instancePath: '',
schemaPath: '#/allOf/0/then/required',
keyword: 'required',
params: { missingProperty: 'interconnectId' },
message: "must have required property 'interconnectId'"
},
{
instancePath: '',
schemaPath: '#/allOf/0/if',
keyword: 'if',
params: { failingKeyword: 'then' },
message: 'must match "then" schema'
}
] */