aggregate

aggregate<R>(fn?: Aggregator<Current, R> | CallableAggregator<Current, R>): RouteBuilder<R>

Combine multiple exchanges into a single result. Useful after split to recombine processed items.

If no aggregator is provided, exchange bodies are automatically collected into an array. If any body is an array, all arrays are flattened and combined with scalar values into a single flattened array.

// Automatically collect bodies into an array
.split()
.process((exchange) => ({ ...exchange, body: exchange.body * 2 }))
.aggregate() // Returns array of processed items: [2, 4, 6]

// Arrays are automatically flattened
// Input: [1, [2, 3], 4, [5, 6]]
// Output: [1, 2, 3, 4, 5, 6] (flattened)

// Mixed arrays and scalars are combined
// Input: [[1, 2], 3, [4, 5]]
// Output: [1, 2, 3, 4, 5] (arrays flattened, scalars added)

// Custom aggregation logic
.aggregate((items) => ({
  totalCount: items.length,
  processedAt: new Date().toISOString(),
  items
}))

Children that do not arrive

A child can miss the aggregate in three ways, and they are not the same outcome:

What happened to the childWhat the aggregate does
.filter() dropped itJoins the others. The route decided to leave it out.
It failed and a handler recovered or dropped itJoins the others. The handler decided.
It failed and nothing handled itDoes not run. The parent exchange fails with RC5001.

In the last case the siblings still finish their own steps first. The parent's error carries the first child's error as its cause, and route:exchange:failed lists the ids of the failed children in failedChildren. The parent's error is retryable only when every failed child's is. The route's .error() handler is asked about the parent's failure like any other, so a route that wants a partial answer says so there or on the child's path. failedChildrenOf(error) returns the failed children's ids for this failure and undefined for any other:

import { craft, direct, failedChildrenOf, recovery } from '@routecraft/routecraft'

export default craft()
  .id('price-order')
  .error((error) =>
    failedChildrenOf(error) ? { priced: false } : recovery.rethrow(),
  )
  .from(direct())
  .split()
  .to(direct('price-check'))
  .aggregate()