68 lines
2.0 KiB
C#
68 lines
2.0 KiB
C#
using MediatR;
|
|
using cuqmbr.TravelGuide.Application.Common.Interfaces.Persistence;
|
|
using AutoMapper;
|
|
using cuqmbr.TravelGuide.Application.Common.Exceptions;
|
|
|
|
namespace cuqmbr.TravelGuide.Application.Buses.Commands.UpdateBus;
|
|
|
|
public class UpdateBusCommandHandler :
|
|
IRequestHandler<UpdateBusCommand, BusDto>
|
|
{
|
|
private readonly UnitOfWork _unitOfWork;
|
|
private readonly IMapper _mapper;
|
|
|
|
public UpdateBusCommandHandler(
|
|
UnitOfWork unitOfWork,
|
|
IMapper mapper)
|
|
{
|
|
_unitOfWork = unitOfWork;
|
|
_mapper = mapper;
|
|
}
|
|
|
|
public async Task<BusDto> Handle(
|
|
UpdateBusCommand request,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
var entity = await _unitOfWork.BusRepository.GetOneAsync(
|
|
e => e.Guid == request.Guid, cancellationToken);
|
|
|
|
if (entity == null)
|
|
{
|
|
throw new NotFoundException();
|
|
}
|
|
|
|
var duplicateEntity = await _unitOfWork.BusRepository.GetOneAsync(
|
|
e => e.Number == request.Number && e.Guid != request.Guid,
|
|
cancellationToken);
|
|
|
|
if (duplicateEntity != null)
|
|
{
|
|
throw new DuplicateEntityException(
|
|
"Bus with given number already exists.");
|
|
}
|
|
|
|
var parentEntity = await _unitOfWork.CompanyRepository.GetOneAsync(
|
|
e => e.Guid == request.CompanyGuid, cancellationToken);
|
|
|
|
if (parentEntity == null)
|
|
{
|
|
throw new NotFoundException(
|
|
$"Parent entity with Guid: {request.CompanyGuid} not found.");
|
|
}
|
|
|
|
entity.Number = request.Number;
|
|
entity.Model = request.Model;
|
|
entity.Capacity = request.Capacity;
|
|
entity.CompanyId = parentEntity.Id;
|
|
entity.Company = parentEntity;
|
|
|
|
entity = await _unitOfWork.BusRepository.UpdateOneAsync(
|
|
entity, cancellationToken);
|
|
|
|
await _unitOfWork.SaveAsync(cancellationToken);
|
|
_unitOfWork.Dispose();
|
|
|
|
return _mapper.Map<BusDto>(entity);
|
|
}
|
|
}
|