diff --git a/modules/backend/src/main/scala/eventsourcing/RepositoryReader.scala b/modules/backend/src/main/scala/eventsourcing/RepositoryReader.scala index 831e5318..09fb7c04 100644 --- a/modules/backend/src/main/scala/eventsourcing/RepositoryReader.scala +++ b/modules/backend/src/main/scala/eventsourcing/RepositoryReader.scala @@ -54,10 +54,11 @@ object RepositoryReader { .flatMap { case Some(last) => journal - .readStreamAfter(streamId, last.version) + .readStreamAfter(streamId, last.version - 1) .through(scanState(last)) .compile .lastOrError + case None => history(streamId).compile.lastOrError } diff --git a/modules/backend/src/test/scala/eventsourcing/RepositoryReaderSuite.scala b/modules/backend/src/test/scala/eventsourcing/RepositoryReaderSuite.scala index c75d06bb..61638e77 100644 --- a/modules/backend/src/test/scala/eventsourcing/RepositoryReaderSuite.scala +++ b/modules/backend/src/test/scala/eventsourcing/RepositoryReaderSuite.scala @@ -69,6 +69,41 @@ class RepositoryReaderSuite extends CatsEffectSuite { ) ) } + + test("Repository reader uses snapshot") { + val snapshot: SnapshotReader[IO, Long] = ConstantSnapshotStore(45, 9) + val journal: JournalReader[IO, Int] = JournalReaderStub(data) + + val r = RepositoryReader(journal, snapshot) + + r.get("sut").assertEquals(AggregateState.Valid(55, 10)) >> + r.history("sut") + .compile + .toList + .assertEquals( + data.scanLeft(initial)((s, e) => + AggregateState.Valid(s.state + e.payload, s.version + 1) + ) + ) + } + + test("Repository reader uses wrong snapshots too!") { + val snapshot: SnapshotReader[IO, Long] = ConstantSnapshotStore(100, 9) + val journal: JournalReader[IO, Int] = JournalReaderStub(data) + + val r = RepositoryReader(journal, snapshot) + + r.get("sut").assertEquals(AggregateState.Valid(110, 10)) >> + r.history("sut") + .compile + .toList + .assertEquals( + data.scanLeft(initial)((s, e) => + AggregateState.Valid(s.state + e.payload, s.version + 1) + ) + ) + } + } class JournalReaderStub[E](data: Stream[IO, EventMessage[E]])