-
-
Save dcomartin/8d6a0863f1760299d5376a157e1ed88d 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 ArriveHandler : IRequestHandler<Arrive> | |
{ | |
private readonly ShipmentDbContext _dbContext; | |
private readonly IBus _bus; | |
public ArriveHandler(ShipmentDbContext dbContext, IBus bus) | |
{ | |
_dbContext = dbContext; | |
_bus = bus; | |
} | |
public async Task<Unit> Handle(Arrive request, CancellationToken cancellationToken) | |
{ | |
var allStops = await _dbContext.Stops.Where(x => x.ShipmentId == request.ShipmentId).ToArrayAsync(); | |
var stop = allStops.SingleOrDefault(x => x.StopId == request.StopId); | |
if (stop == null) | |
{ | |
throw new InvalidOperationException("Stop does not exist."); | |
} | |
if (stop.Status != StopStatus.InTransit) | |
{ | |
throw new InvalidOperationException("Stop has already arrived."); | |
} | |
var previousStopsAreNotDeparted = allStops | |
.Where(x => x.Scheduled < stop.Scheduled) | |
.Any(x => x.Status != StopStatus.Departed); | |
if (previousStopsAreNotDeparted) | |
{ | |
throw new InvalidOperationException("Previous stops have not departed."); | |
} | |
stop.Status = StopStatus.Arrived; | |
stop.Arrived = request.Arrived; | |
await _dbContext.SaveChangesAsync(); | |
await _bus.Publish(new Arrived(stop.StopId, stop.Arrived)); | |
return Unit.Value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment