http-api/src/Application/Regions/Commands/AddRegion/AddRegionCommandHandler.cs
2025-04-29 23:51:19 +03:00

61 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.Regions.Commands.AddRegion;
public class AddRegionCommandHandler :
IRequestHandler<AddRegionCommand, RegionDto>
{
private readonly UnitOfWork _unitOfWork;
private readonly IMapper _mapper;
public AddRegionCommandHandler(
UnitOfWork unitOfWork,
IMapper mapper)
{
_unitOfWork = unitOfWork;
_mapper = mapper;
}
public async Task<RegionDto> Handle(
AddRegionCommand request,
CancellationToken cancellationToken)
{
var entity = await _unitOfWork.RegionRepository.GetOneAsync(
e => e.Name == request.Name && e.Country.Guid == request.CountryUuid,
cancellationToken);
if (entity != null)
{
throw new DuplicateEntityException(
"Region with given name already exists.");
}
var parentEntity = await _unitOfWork.CountryRepository.GetOneAsync(
e => e.Guid == request.CountryUuid, cancellationToken);
if (parentEntity == null)
{
throw new NotFoundException(
$"Parent entity with Guid: {request.CountryUuid} not found.");
}
entity = new Region()
{
Name = request.Name,
CountryId = parentEntity.Id
};
entity = await _unitOfWork.RegionRepository.AddOneAsync(
entity, cancellationToken);
await _unitOfWork.SaveAsync(cancellationToken);
_unitOfWork.Dispose();
return _mapper.Map<RegionDto>(entity);
}
}