From 48664c35b2e583aeacfcacd5d740687afb2ed1de Mon Sep 17 00:00:00 2001 From: Debasish Ghosh Date: Tue, 23 Aug 2016 00:31:01 +0530 Subject: [PATCH] Fixed a bug in event sourced implementation where the first event was materialized before task execution --- .../ch8/cqrs/service/AccountService.scala | 80 +++++++++++-------- 1 file changed, 48 insertions(+), 32 deletions(-) diff --git a/src/main/scala/frdomain/ch8/cqrs/service/AccountService.scala b/src/main/scala/frdomain/ch8/cqrs/service/AccountService.scala index 8884bd3..d8f0e44 100644 --- a/src/main/scala/frdomain/ch8/cqrs/service/AccountService.scala +++ b/src/main/scala/frdomain/ch8/cqrs/service/AccountService.scala @@ -109,38 +109,46 @@ object RepositoryBackedAccountInterpreter extends RepositoryBackedInterpreter { private def handleCommand[A](e: Event[A]): Task[A] = e match { - case o @ Opened(no, name, odate, _) => validateOpen(no).fold( - err => fail(new RuntimeException(err)), - _ => now { - val a = Account(no, name, odate.get) - eventLog.put(no, o) - a - } - ) - - case c @ Closed(no, cdate, _) => validateClose(no, cdate).fold( - err => fail(new RuntimeException(err)), - currentState => now { - eventLog.put(no, c) - updateState(c, currentState)(no) - } - ) - - case d @ Debited(no, amount, _) => validateDebit(no, amount).fold( - err => fail(new RuntimeException(err)), - currentState => now { - eventLog.put(no, d) - updateState(d, currentState)(no) - } - ) - - case r @ Credited(no, amount, _) => validateCredit(no).fold( - err => fail(new RuntimeException(err)), - currentState => now { - eventLog.put(no, r) - updateState(r, currentState)(no) - } - ) + case o @ Opened(no, name, odate, _) => Task { + validateOpen(no).fold( + err => throw new RuntimeException(err), + _ => { + val a = Account(no, name, odate.get) + eventLog.put(no, o) + a + } + ) + } + + case c @ Closed(no, cdate, _) => Task { + validateClose(no, cdate).fold( + err => throw new RuntimeException(err), + currentState => { + eventLog.put(no, c) + updateState(c, currentState)(no) + } + ) + } + + case d @ Debited(no, amount, _) => Task { + validateDebit(no, amount).fold( + err => throw new RuntimeException(err), + currentState => { + eventLog.put(no, d) + updateState(d, currentState)(no) + } + ) + } + + case r @ Credited(no, amount, _) => Task { + validateCredit(no).fold( + err => throw new RuntimeException(err), + currentState => { + eventLog.put(no, r) + updateState(r, currentState)(no) + } + ) + } } } @@ -166,4 +174,12 @@ object Scripts extends AccountCommands { _ <- credit(a.no, 30000) d <- debit(a.no, 50000) } yield d + + val comp = + for { + a <- open("a1", "debasish ghosh", Some(today)) + _ <- credit(a.no, 10000) + _ <- credit(a.no, 30000) + d <- debit(a.no, 23000) + } yield d }