-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPullRequestEventProcessor.cs
50 lines (39 loc) · 1.68 KB
/
PullRequestEventProcessor.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// Copyright (c) Arjen Post. See LICENSE in the project root for license information.
using System.Collections.Immutable;
using Giddup.ApplicationCore.Application.PullRequests;
using Giddup.ApplicationCore.Domain.PullRequests;
using Giddup.Infrastructure.PullRequests.QueryModel.Models;
using Microsoft.EntityFrameworkCore;
namespace Giddup.Infrastructure.PullRequests.CommandModel;
public class PullRequestEventProcessor : IPullRequestEventProcessor
{
private readonly GiddupDbContext _dbContext;
public PullRequestEventProcessor(GiddupDbContext dbContext)
=> _dbContext = dbContext;
public async Task<bool> Process(Guid pullRequestId, long? expectedVersion, ImmutableList<IPullRequestEvent> events)
{
var currentVersion = await GetCurrentVersion(pullRequestId);
if (currentVersion != expectedVersion)
{
return false;
}
var version = currentVersion ?? 0;
_dbContext.Events
.AddRange(events
.Select(@event => new Event
{
AggregateId = pullRequestId,
AggregateType = nameof(PullRequest),
AggregateVersion = ++version,
Type = @event.GetType().Name,
Data = PullRequestEventSerializer.Serialize(@event)
}));
_ = await _dbContext.SaveChangesAsync();
return true;
}
private Task<long?> GetCurrentVersion(Guid pullRequestId)
=> _dbContext.Events
.Where(@event => @event.AggregateId == pullRequestId)
.Select(@event => @event.AggregateVersion)
.MaxAsync(aggregateVersion => (long?)aggregateVersion);
}