Created
September 5, 2019 01:01
-
-
Save dcomartin/81c33b1e772f90ac931d390754b48330 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class BalanceProjection | |
{ | |
private readonly IEventMap<Balance> _map; | |
public Balance Balance { get; } = new Balance(0, DateTime.UtcNow); | |
public BalanceProjection(IStreamStore streamStore, StreamId streamId) | |
{ | |
var mapBuilder = new EventMapBuilder<Balance>(); | |
mapBuilder.Map<Deposited>().As((deposited, balance) => | |
{ | |
balance.Add(deposited.Amount); | |
}); | |
mapBuilder.Map<Withdrawn>().As((withdrawn, balance) => | |
{ | |
balance.Subtract(withdrawn.Amount); | |
}); | |
_map = mapBuilder.Build(new ProjectorMap<Balance>() | |
{ | |
Custom = (context, projector) => projector() | |
}); | |
streamStore.SubscribeToStream(streamId, null, StreamMessageReceived); | |
} | |
private async Task<object> DeserializeJsonEvent(StreamMessage streamMessage, CancellationToken cancellationToken) | |
{ | |
var json = await streamMessage.GetJsonData(cancellationToken); | |
switch (streamMessage.Type) | |
{ | |
case "Deposited": | |
return JsonConvert.DeserializeObject<Deposited>(json); | |
case "Withdrawn": | |
return JsonConvert.DeserializeObject<Withdrawn>(json); | |
default: | |
throw new InvalidOperationException("Unknown event type."); | |
} | |
} | |
private async Task StreamMessageReceived(IStreamSubscription subscription, StreamMessage streamMessage, CancellationToken cancellationToken) | |
{ | |
var @event = await DeserializeJsonEvent(streamMessage, cancellationToken); | |
await _map.Handle(@event, Balance); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment