diff --git a/WarehouseProduct.cs b/WarehouseProduct.cs index d52ee43..0289a5c 100644 --- a/WarehouseProduct.cs +++ b/WarehouseProduct.cs @@ -88,7 +88,7 @@ _allEvents.Add(evnt); } - public void AddEvent(IEvent evnt) + private void AddEvent(IEvent evnt) { ApplyEvent(evnt); _uncommittedEvents.Add(evnt); diff --git a/WarehouseProduct.cs b/WarehouseProduct.cs index d52ee43..0289a5c 100644 --- a/WarehouseProduct.cs +++ b/WarehouseProduct.cs @@ -88,7 +88,7 @@ _allEvents.Add(evnt); } - public void AddEvent(IEvent evnt) + private void AddEvent(IEvent evnt) { ApplyEvent(evnt); _uncommittedEvents.Add(evnt); diff --git a/WarehouseProductRepository.cs b/WarehouseProductRepository.cs index ea2234d..41609b3 100644 --- a/WarehouseProductRepository.cs +++ b/WarehouseProductRepository.cs @@ -12,7 +12,7 @@ { public class WarehouseProductEventStoreStream { - private const int SnapshotInterval = 1; + private const int SnapshotInterval = 4; private readonly IEventStoreConnection _connection; public static async Task Factory() @@ -92,26 +92,6 @@ return new Snapshot(); } - public async Task Save(WarehouseProduct warehouseProduct) - { - var streamName = GetStreamName(warehouseProduct.Sku); - - var newEvents = warehouseProduct.GetUncommittedEvents(); - foreach (var evnt in newEvents) - { - var data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(evnt)); - var metadata = Encoding.UTF8.GetBytes("{}"); - var evt = new EventData(Guid.NewGuid(), evnt.EventType, true, data, metadata); - var result = await _connection.AppendToStreamAsync(streamName, ExpectedVersion.Any, evt); - - if ((result.NextExpectedVersion - 1) % SnapshotInterval == 0) - { - await AppendSnapshot(warehouseProduct, result.NextExpectedVersion); - } - } - - } - private IEvent DeserializeEvent(ResolvedEvent evnt) { var json = Encoding.UTF8.GetString(evnt.Event.Data); @@ -124,6 +104,27 @@ }; } + public async Task Save(WarehouseProduct warehouseProduct) + { + var streamName = GetStreamName(warehouseProduct.Sku); + + var newEvents = warehouseProduct.GetUncommittedEvents(); + long version = 0; + foreach (var evnt in newEvents) + { + var data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(evnt)); + var metadata = Encoding.UTF8.GetBytes("{}"); + var evt = new EventData(Guid.NewGuid(), evnt.EventType, true, data, metadata); + var result = await _connection.AppendToStreamAsync(streamName, ExpectedVersion.Any, evt); + version = result.NextExpectedVersion; + } + + if ((version + 1) >= SnapshotInterval && (version + 1) % SnapshotInterval == 0) + { + await AppendSnapshot(warehouseProduct, version); + } + } + private async Task AppendSnapshot(WarehouseProduct warehouseProduct, long version) { var streamName = GetSnapshotStreamName(warehouseProduct.Sku); @@ -149,7 +150,7 @@ public class Snapshot { - public long Version { get; set; } = 0; + public long Version { get; set; } = -1; public WarehouseProductState State { get; set; } = new(); } } \ No newline at end of file