OnCommand
Marks a function as a command handler within an aggregate.
Functions annotated with @OnCommand are responsible for processing commands and producing domain events that represent state changes. They are the primary way aggregates respond to business operations.
Command handlers should:
Validate command data and business rules
Access and modify aggregate state
Return domain events representing the changes
Be idempotent when possible
Follow the command-query separation principle
Example usage:
@AggregateRoot
class OrderAggregate(
@AggregateId
val orderId: String
) {
@OnCommand(returns = [OrderCreated::class])
fun create(command: CreateOrderCommand): OrderCreated {
require(command.items.isNotEmpty()) { "Order must have items" }
return OrderCreated(
orderId = command.orderId,
customerId = command.customerId,
items = command.items,
total = calculateTotal(command.items)
)
}
@OnCommand
fun addItem(command: AddOrderItemCommand): OrderItemAdded {
// Business logic for adding items
return OrderItemAdded(command.orderId, command.item)
}
}Parameters
Array of event types that this handler may produce. Used for documentation and validation. Framework automatically infers return types when not specified.
See also
for aggregate classes containing command handlers
for event handlers
for the command processing implementation