62 lines
1.7 KiB
C#
62 lines
1.7 KiB
C#
using MediatR;
|
|
using cuqmbr.TravelGuide.Application.Common.Interfaces.Persistence;
|
|
using cuqmbr.TravelGuide.Domain.Entities;
|
|
using AutoMapper;
|
|
using cuqmbr.TravelGuide.Application.Common.Exceptions;
|
|
|
|
namespace cuqmbr.TravelGuide.Application.Cities.Commands.AddCity;
|
|
|
|
public class AddCityCommandHandler :
|
|
IRequestHandler<AddCityCommand, CityDto>
|
|
{
|
|
private readonly UnitOfWork _unitOfWork;
|
|
private readonly IMapper _mapper;
|
|
|
|
public AddCityCommandHandler(
|
|
UnitOfWork unitOfWork,
|
|
IMapper mapper)
|
|
{
|
|
_unitOfWork = unitOfWork;
|
|
_mapper = mapper;
|
|
}
|
|
|
|
public async Task<CityDto> Handle(
|
|
AddCityCommand request,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
var entity = await _unitOfWork.CityRepository.GetOneAsync(
|
|
e => e.Name == request.Name && e.Region.Guid == request.RegionGuid,
|
|
cancellationToken);
|
|
|
|
if (entity != null)
|
|
{
|
|
throw new DuplicateEntityException(
|
|
"City with given name already exists.");
|
|
}
|
|
|
|
var parentEntity = await _unitOfWork.RegionRepository.GetOneAsync(
|
|
e => e.Guid == request.RegionGuid, e => e.Country,
|
|
cancellationToken);
|
|
|
|
if (parentEntity == null)
|
|
{
|
|
throw new NotFoundException(
|
|
$"Parent entity with Guid: {request.RegionGuid} not found.");
|
|
}
|
|
|
|
entity = new City()
|
|
{
|
|
Name = request.Name,
|
|
RegionId = parentEntity.Id
|
|
};
|
|
|
|
entity = await _unitOfWork.CityRepository.AddOneAsync(
|
|
entity, cancellationToken);
|
|
|
|
await _unitOfWork.SaveAsync(cancellationToken);
|
|
_unitOfWork.Dispose();
|
|
|
|
return _mapper.Map<CityDto>(entity);
|
|
}
|
|
}
|