Skip to main content

Conditionals

Both types are exported from the main package:

import type { Conditional, ConditionContext } from '@caffeine-projects/dicaf'

Conditional

type Conditional = (ctx: ConditionContext) => boolean | Promise<boolean>

A predicate evaluated once during init(). When it returns false, the binding is skipped — it is not registered in the container for that run.

Used by:

// synchronous
const hasRedis: Conditional = ctx => ctx.container.has(RedisClient)

// async
const featureEnabled: Conditional = async ctx => {
const flags = ctx.container.get(FeatureFlags)
return flags.isEnabled('new-cache')
}

Multiple predicates passed to .conditional() are ANDed — all must return true for the binding to be registered.


ConditionContext

interface ConditionContext {
readonly container: {
has(key: Key): boolean
}
readonly key: Key
readonly binding: BindingDecoratorConfig
}

Passed to every Conditional predicate at evaluation time.

PropertyDescription
container.hasChecks whether a binding is registered for the given key.
keyThe key of the binding being tested.
bindingThe full decorator config for the binding: scope, name, labels, tags, and other metadata set by decorators.
// guard on another binding being present
di.bind(RedisCacheService)
.toSelf()
.conditional(ctx => ctx.container.has(RedisClient))

// inspect the binding's own key
di.bind(MetricsReporter)
.toSelf()
.conditional(ctx => ctx.key !== Symbol.for('noop'))