Skip to content

Instantly share code, notes, and snippets.

@dcomartin
Created March 16, 2022 21:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dcomartin/13574494f06dfd0e68d6119ff896f12f to your computer and use it in GitHub Desktop.
Save dcomartin/13574494f06dfd0e68d6119ff896f12f to your computer and use it in GitHub Desktop.
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