Skip to content

Commit

Permalink
Merge pull request #52 from jacqueskang/refactor
Browse files Browse the repository at this point in the history
refactor: return changeset object when saving aggregate; remove call …
  • Loading branch information
jacqueskang authored Feb 9, 2020
2 parents d0ab17f + 43e00ec commit d0935b1
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 10 deletions.
7 changes: 7 additions & 0 deletions src/JKang.EventSourcing.Abstractions/Domain/Aggregate.cs
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,7 @@ private void IntegrateSnapshot(IAggregateSnapshot<TKey> snapshot)
internal class Changeset : IAggregateChangeset<TKey>
{
private readonly Aggregate<TKey> _aggregate;
private bool _committed = false;

public Changeset(
Aggregate<TKey> aggregate,
Expand All @@ -182,13 +183,19 @@ public Changeset(

public void Commit()
{
if (_committed)
{
throw new InvalidOperationException("The changeset is already committed");
}

for (int i = 0; i < Events.Count(); i++)
{
IAggregateEvent<TKey> @evt = _aggregate._unsavedEvents.Dequeue();
_aggregate._savedEvents.Enqueue(@evt);
}

_aggregate._unsavedSnapshot = null;
_committed = true;
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using JKang.EventSourcing.Events;
using JKang.EventSourcing.Snapshotting;
using System.Collections.Generic;

namespace JKang.EventSourcing.Domain
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ protected AggregateRepository(
_snapshotStore = snapshotStore ?? throw new ArgumentNullException(nameof(snapshotStore));
}

protected async Task SaveAggregateAsync(TAggregate aggregate,
protected async Task<IAggregateChangeset<TKey>> SaveAggregateAsync(TAggregate aggregate,
CancellationToken cancellationToken = default)
{
if (aggregate is null)
Expand All @@ -35,24 +35,17 @@ protected async Task SaveAggregateAsync(TAggregate aggregate,
foreach (IAggregateEvent<TKey> @event in changeset.Events)
{
await _eventStore.AddEventAsync(@event, cancellationToken).ConfigureAwait(false);
await OnEventSavedAsync(@event, cancellationToken).ConfigureAwait(false);
}

if (changeset.Snapshot != null)
{
await _snapshotStore.AddSnapshotAsync(changeset.Snapshot, cancellationToken).ConfigureAwait(false);
await OnSnapshotSavedAsync(changeset.Snapshot, cancellationToken).ConfigureAwait(false);
}

changeset.Commit();
return changeset;
}

protected virtual Task OnEventSavedAsync(IAggregateEvent<TKey> e,
CancellationToken cancellationToken = default) => Task.CompletedTask;

protected virtual Task OnSnapshotSavedAsync(IAggregateSnapshot<TKey> snapshot,
CancellationToken cancellationToken = default) => Task.CompletedTask;

protected Task<TKey[]> GetAggregateIdsAsync()
{
return _eventStore.GetAggregateIdsAsync();
Expand Down

0 comments on commit d0935b1

Please sign in to comment.