Skip to content

Instantly share code, notes, and snippets.

@dcomartin
Created Mar 16, 2022
Embed
What would you like to do?
public class PickupHandler : IRequestHandler<Pickup>
{
private readonly ShipmentDbContext _dbContext;
private readonly IBus _bus;
public PickupHandler(ShipmentDbContext dbContext, IBus bus)
{
_dbContext = dbContext;
_bus = bus;
}
public async Task<Unit> Handle(Pickup request, CancellationToken cancellationToken)
{
var stop = await _dbContext.Stops.SingleOrDefaultAsync(x => x.StopId == request.StopId);
if (stop == null)
{
throw new InvalidOperationException("Stop does not exist.");
}
if (stop.Status == StopStatus.Departed)
{
throw new InvalidOperationException("Stop has already departed.");
}
// If they haven't arrived yet, let's allow them to perform this action, and we'll just set the
// Arrived datetime to our departed DateTime
if (stop.Status == StopStatus.InTransit)
{
// Gotcha! Now we've made a state change without publishing an Arrived event.
stop.Arrived = request.Departed;
}
if (request.Departed < stop.Arrived)
{
throw new InvalidOperationException("Departed Date/Time cannot be before Arrived Date/Time.");
}
stop.Status = StopStatus.Departed;
stop.Departed = request.Departed;
await _dbContext.SaveChangesAsync();
await _bus.Publish(new PickedUp(request.StopId, request.Departed));
return Unit.Value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment