Skip to main content

first

$first

An operator that returns the first defined value successfully returned from a sequence of processors.

Unlike $any, no exception is thrown if there are no defined results, it simply returns undefined. Be careful to not use this in a situation where the provided processors may require late-resolved values! This works best in finalizers, validators, or in opaque schema transformers.

There is no truthy variant of $first, as there generally isn't much value in differentiating which truthy value to return; use constructs like {$if: {$or: [...]}} to wrap truthy sequence constraints as operators. $first is basically an alias for {$gate: {$any: [...]}}.

Parameters

  • processors (Array<ProcessorSpec>, required): Array of processor specifications to try in order.

Example

// Try several environment variable names and return the first one that has a value
new Schema('object').transformer({
$first: [
{$reference: 'DATABASE_URL'},
{$reference: 'DB_URL'},
{$reference: 'POSTGRES_URL'},
]
})

// Return the first successfully parsed format
new Schema('string').normalizer({
$first: ['$number', '$date', '$boolean']
})