function composeBehaviorChain
Since 0.3.0
composeBehaviorChain<TWork, TResult>(
work: TWork,
behaviors: readonly BehaviorLike<TWork, TResult>[],
terminal: () => Promise<TResult>
): Promise<TResult>

Composes behaviours around a terminal handler — the ONE shared composer for the CQRS pipeline and all four non-HTTP ingress chains.

Behaviors are wrapped last-to-first so behaviors[0] runs first (declared order = execution order). A behaviour short-circuits by returning without calling next(), which skips the downstream behaviours and the terminal. A behaviour that throws — synchronously or asynchronously — REJECTS the returned promise, propagating to that ingress's existing failure path. An empty array invokes the terminal exactly once.

The implementation converts every synchronous throw into a rejected promise: the declared return type is a promise, and a caller writing .catch(...) — or Promise.allSettled over a batch — must see every failure.

Examples

Example 1

const behaviors: readonly IIngressBehavior[] = [new TenantBehavior()];
await composeBehaviorChain<IngressContext, void>(
  {
    kind: 'queue',
    name: job.name,
    payload: job.data,
    attempt: job.attempts,
  },
  behaviors,
  () => processor(job),
);

Type Parameters

TWork

The work item being handled

TResult

The chain result type

Parameters

work: TWork

The work item being handled

behaviors: readonly BehaviorLike<TWork, TResult>[]

Behaviors to apply, in declared order

terminal: () => Promise<TResult>

The terminal handler, invoked exactly once when no behaviour short-circuits

Return Type

Promise<TResult>

The result of the chain: the terminal's result, or the short-circuiting behaviour's return value

Throws

Error

— as a REJECTION, never synchronously: a behaviour's throw propagates to the caller

Usage

import { composeBehaviorChain } from "common/src/index.ts";