Skip to main content

check

$check

This is a conditional operator that evaluates a predicate for truthiness.

If the predicate returns a truthy value, $check 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 a falsey value or rejects/throws, $check 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 already falsey, 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.

Parameters

  • predicate (processor, optional): Evaluated for truthiness. The predicate result (not the original input) is passed to success/failure.
  • success (processor, optional): Invoked with the predicate result on truthy outcome. Default: returns predicate result.
  • failure (processor, optional): Invoked with the predicate result on falsey outcome or throw. Default: returns undefined.

Array form: {$check: [predicate, success, failure]} Object form: {$check: {predicate: ..., success: ..., failure: ...}}

Example

// Extract and validate an environment key, returning the matched value or undefined
new Schema('string').transformer({
$check: [
{$match: /^(production|staging|development)$/},
]
})

// Validate a regex match and throw on failure
new Schema('string').validator({
$check: [
{$match: /^\d{4}-\d{2}-\d{2}$/},
null,
() => { throw new Error('Expected YYYY-MM-DD date format') }
]
})