if
$if
This is a conditional operator that evaluates a predicate for truthiness.
If the predicate returns a truthy value, $if will invoke any provided success action with the original input. If not provided, the default success action will simply return the original input.
If the predicate returns a falsey value or rejects/throws, $if will return the result of invoking the failure action on the original input. The default failure action will return undefined.
This processor can act as a constraint if the success or failure actions throw when triggered.
To pass the predicate results to the actions instead of the input, see $check. To test for success rather than truthiness, see $gate.
Parameters
predicate(processor, optional): Evaluated for truthiness. If omitted, the input itself is used as the predicate.success(processor, optional): Invoked with the original input on truthy predicate result. Default: returns input as-is.failure(processor, optional): Invoked with the original input on falsey predicate result or throw. Default: returns undefined.
Array form: {$if: [predicate, success, failure]}
Object form: {$if: {predicate: ..., success: ..., failure: ...}}
Aliases: predicate may also be written as condition or cond.
Example
// Normalize an optional port — keep it if numeric, otherwise drop it
new Schema('object', {
port: new Schema('number').normalizer({
$if: ['$numeric', '$number', null]
}),
})
// Conditionally require an API key when a flag is set
new Schema('object', {
useApiKey: new Schema('boolean'),
apiKey: new Schema('string').validator({
$if: [
{$reference: 'useApiKey'},
'$non-empty',
]
}),
})