Kest

Search

Search the documentation

Recipes

CQRS

Command, query and event buses, aggregates, and sagas written as functions or as event streams.

cqrs is @nestjs/cqrs: one bus per kind of message, found by annotations at build time.

class CreateOrder(val id: String, val item: String)
class GetOrder(val id: String)
class OrderCreated(val id: String)
 
@Injectable
class OrderHandlers(private val publisher: EventPublisher) {
    @CommandHandler fun create(c: CreateOrder): String {
        store[c.id] = Order(c.id, c.item)
        publisher.mergeObjectContext(OrderAggregate(c.id).also { it.place() }).commit()    // publishes what the aggregate recorded
        return c.id
    }
    @QueryHandler fun get(q: GetOrder): Order? = store[q.id]
    @EventsHandler fun onCreated(e: OrderCreated) { /* any number of handlers per event */ }
}
 
commands.execute<String>(CreateOrder("o1", "boots"))
queries.execute<Order>(GetOrder("o1"))
events.publish(OrderCreated("o1"))

@CommandHandler and @QueryHandler allow exactly one handler per type (two is a startup error); events go to every matching handler, subtypes included. Import CqrsModule.forRoot().

Sagas

A saga turns events into commands. Two forms.

A function: one event in, a command, a list of commands, or null out.

@Saga fun onPaid(e: OrderPaid): Any? = ShipOrder(e.orderId)

A stream, as in NestJS where a saga receives and returns an Observable:

@Saga fun reminders(events: Stream<Any>): Stream<*> =
    events.ofType(CartEdited::class).debounce(Duration.ofMinutes(30)).map { RemindCustomer(it.cart) }
 
@Saga fun shipLater(events: Stream<Any>): Stream<*> =
    events.ofType(OrderPaid::class).delay(Duration.ofSeconds(2)).map { ShipOrder(it.orderId) }
 
@Saga fun batches(events: Stream<Any>): Stream<*> =
    events.ofType(CartEdited::class).filter { it.n == 0 }.map { it.cart }.buffer(3).map { Batch(it) }

Operators: ofType, filter, map, flatMap, tap, take, distinctUntilChanged, delay, debounce, throttleFirst, buffer(count), bufferTime(duration), merge. Whatever the final stream emits (a command, or a collection of commands) runs on the command bus; a failing command is logged and the stream carries on.

Streams are hot and thread-safe: events published from many threads at once are handled, and the stateful operators (debounce, buffer, throttleFirst...) synchronise themselves. Time operators use one shared timer thread and hand values on from it, so publish never waits for a delayed saga.

Different from RxJS

This is a small push stream, not RxJS: there is no backpressure, no switchMap, combineLatest or retry, and no cold streams. For heavier pipelines use a queue.