Slide 66
Slide 66 text
実装例
persistenceIdは集約IDを指定する
Stateには、ドメインオブジェクトを格納する
コマンドの処理はコマンドハンドラでイベントの処理はイベントハンドラで⾏う
sealed trait Command
final case class Add(data: String) extends Command
case object Clear extends Command
sealed trait Event
final case class Added(data: String) extends Event
case object Cleared extends Event
final case class State(history: List[String] = Nil)
def apply(id: String): Behavior[Command] =
EventSourcedBehavior[Command, Event, State](
persistenceId = PersistenceId.ofUniqueId(id),
// 綬耗ID
emptyState = State(Nil), // 綬耗げ訟尊
commandHandler, // りヂプキコプキネ
eventHandler) // ほソプガコプキネ
private val commandHandler: (State, Command) =>
Effect[Event, State] = { (state, command) =>
command match {
case Add(data) => Effect.persist(Added(data))
case Clear => Effect.persist(Cleared)
}
}
private val eventHandler: (State, Event) => State = {
(state, event) =>
event match {
case Added(data) => state.copy((data ::
state.history).take(5))
case Cleared => State(Nil)
}
}
66