There is the following method that should get record from the database, apply new data, and if at least one value has been changed, update database and send event
We don't use EntityFramework, it uses CosmosDb SDK in the repository.
I'm not sure how is the proper way to implement hasChanges
.
public async Task<Unit> Handle(ChangeLiftStateCommand request, CancellationToken cancellationToken)
{
Lift lift = await _repository.Get(request.Number, cancellationToken)
?? throw new NotFoundException(request.Number);
bool hasChanges = false;
if (Enum.TryParse(request.HealthState, ignoreCase: true, out HealthState healthState))
{
if (lift.State.HealthState != healthState)
{
lift.State.HealthState = healthState;
hasChanges = true;
}
}
if (lift.State.GenericState != request.GenericState)
{
lift.State.GenericState = request.GenericState;
hasChanges = true;
}
if (request.CabinPosition.HasValue)
{
Cabin cabin = lift.Cabins.FirstOrDefault(c => c.Type == CabinType.Main);
if (cabin is null)
{
lift.Cabins.Add(new Cabin
{
Deck = Deck.Lower,
Position = request.CabinPosition.Value
});
hasChanges = true;
}
else
{
if (cabin.Position != request.CabinPosition.Value)
{
cabin.Position = request.CabinPosition.Value;
hasChanges = true;
}
}
}
if (hasChanges)
{
await _repository.Update(lift);
await _eventProducer.Send(new LiftChangedEvent
{
Number = request.Number,
CabinPosition = request.CabinPosition,
HealthState = request.HealthState,
GenericState = request.GenericState
});
}
return Unit.Value;
}
Could you please advice how it can be refactored? Are there any pattern for hasChanges
implementation?
Thank you in advance