when
$when
This is a conditional operator that evaluates a predicate for whether it returns a defined value.
If the predicate returns a defined value, $when will return the result of invoking any provided success action with the predicate result. If not provided, the default success action will simply return the predicate result.
If the predicate returns undefined or rejects/throws, $when will return the result of invoking the failure action on the predicate result. The default failure action will return undefined. Since the predicate result is undefined, the failure action is best used to either return a default value or throw an error.
This processor can act as a constraint if the success or failure actions throw when triggered.
To check truthiness instead of defined/undefined, see $check. To pass the original input to the actions instead of the predicate result, see $gate.
Parameters
predicate(processor, optional): Evaluated for defined-ness. The predicate result (not the original input) is passed to success/failure.success(processor, optional): Invoked with the predicate result when it is defined. Default: returns predicate result.failure(processor, optional): Invoked with the predicate result (undefined) when predicate returns undefined or throws. Default: returns undefined.
Array form: {$when: [predicate, success, failure]}
Object form: {$when: {predicate: ..., success: ..., failure: ...}}
Example
// Extract a nested value, providing a default when not found
new Schema('object').transformer({
$when: [
{$get: 'config.timeout'},
null,
() => 5000 // default 5s when config.timeout not set
]
})
// Chain: extract the match groups object if the pattern matched, otherwise drop
new Schema('string').transformer({
$when: [{$match: /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/}]
})