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();
export const schema = 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))
)
);
// notice how the only field changing is "format":
const text = {
format: 'text',
textOutput: { pretty: false },
jsonOutput: { indent: 4 }
};
console.log( await schema.process(text) );
// -> { format: 'text', textOutput: { pretty: false } }
const json = {
format: 'json',
textOutput: { pretty: false },
jsonOutput: { indent: 4 }
};
console.log( await schema.process(json) );
// -> { format: 'json', jsonOutput: { indent: 4 } }
Conditions are useful for ensuring that the output data only contains relevant values.