Conditions
The condition handler determines whether to evaluate the schema at all.
Conditions take precedence even over any default value or required flag.
(Schema evaluation defaults to true if no condition exists.)
Unlike most handlers where any returned value implies success, the return value of the condition handler is evaluated
for truthiness to determine whether to proceed with processing.
Here's an example where sub-schemas are conditionally activated1 depending on a property value:
import { Schema, SchemaResolver} from '@versionzero/schema';
const resolver = new SchemaResolver();
const schema = await resolver.compile(
new Schema('object')
.property('format', new Schema('string')
.validator({$in: ['text', 'json']})
.required()
)
.property('textOutput', new Schema('object')
.condition([{$reference: '/format'}, {$eq: 'text'}])
.property('pretty', new Schema('boolean').default(true))
)
.property('jsonOutput', new Schema('object')
.condition([{$reference: '/format'}, {$eq: 'json'}])
.property('indent', new Schema('number').default(2))
)
);
// initial configuration...
const config = {
format: 'text',
textOutput: { pretty: false },
jsonOutput: { indent: 4 }
};
console.log( await schema.process(config) );
// -> { format: 'text', textOutput: { pretty: false } }
console.log( await schema.process({...config, format: 'json'}) ); // override format
// -> { format: 'json', jsonOutput: { indent: 4 } }
Conditions are useful for ensuring that the output data only contains relevant values.