Last active
August 29, 2015 14:14
-
-
Save yreynhout/74b3bd2c844e1c7dfd12 to your computer and use it in GitHub Desktop.
Goodbye repository, Hello aggregate reader!
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 AggregateReader | |
{ | |
private readonly Func<IAggregateRootEntity> _rootFactory; | |
private readonly IEventStoreConnection _connection; | |
private readonly EventStoreReaderConfiguration _configuration; | |
public AggregateReader( | |
Func<IAggregateRootEntity> rootFactory, | |
IEventStoreConnection connection, | |
EventStoreReaderConfiguration configuration) | |
{ | |
if (rootFactory == null) throw new ArgumentNullException("rootFactory"); | |
if (connection == null) throw new ArgumentNullException("connection"); | |
if (configuration == null) throw new ArgumentNullException("configuration"); | |
_rootFactory = rootFactory; | |
_connection = connection; | |
_configuration = configuration; | |
} | |
public async Task<ReadResult<Aggregate>> ReadAsync(string identifier) | |
{ | |
if (identifier == null) throw new ArgumentNullException("identifier"); | |
var stream = _configuration.StreamNameResolver.Resolve(identifier); | |
var streamCredentials = _configuration.StreamUserCredentialsResolver.Resolve(stream); | |
var slice = await _connection. | |
ReadStreamEventsForwardAsync(stream, StreamPosition.Start, _configuration.SliceSize, false, streamCredentials); | |
if (slice.Status == SliceReadStatus.StreamNotFound) | |
return ReadResult<Aggregate>.NotFound; | |
if (slice.Status == SliceReadStatus.StreamDeleted) | |
return ReadResult<Aggregate>.Deleted; | |
var root = _rootFactory(); | |
root.Initialize(slice.Events.Select(@event => _configuration.Deserializer.Deserialize(@event))); | |
while (!slice.IsEndOfStream) | |
{ | |
slice = await _connection. | |
ReadStreamEventsForwardAsync(stream, slice.NextEventNumber, _configuration.SliceSize, false, streamCredentials); | |
if (slice.Status == SliceReadStatus.StreamNotFound) | |
return ReadResult<Aggregate>.NotFound; | |
if (slice.Status == SliceReadStatus.StreamDeleted) | |
return ReadResult<Aggregate>.Deleted; | |
root.Initialize(slice.Events.Select(@event => _configuration.Deserializer.Deserialize(@event))); | |
} | |
return new ReadResult<Aggregate>(new Aggregate(identifier, slice.LastEventNumber, root)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment