65 lines
1.9 KiB
C#
65 lines
1.9 KiB
C#
using MediatR;
|
|
using cuqmbr.TravelGuide.Application.Common.Persistence;
|
|
using cuqmbr.TravelGuide.Domain.Entities;
|
|
using AutoMapper;
|
|
using cuqmbr.TravelGuide.Application.Common.Exceptions;
|
|
|
|
namespace cuqmbr.TravelGuide.Application.Addresses.Commands.AddAddress;
|
|
|
|
public class AddAddressCommandHandler :
|
|
IRequestHandler<AddAddressCommand, AddressDto>
|
|
{
|
|
private readonly UnitOfWork _unitOfWork;
|
|
private readonly IMapper _mapper;
|
|
|
|
public AddAddressCommandHandler(
|
|
UnitOfWork unitOfWork,
|
|
IMapper mapper)
|
|
{
|
|
_unitOfWork = unitOfWork;
|
|
_mapper = mapper;
|
|
}
|
|
|
|
public async Task<AddressDto> Handle(
|
|
AddAddressCommand request,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
var entity = await _unitOfWork.AddressRepository.GetOneAsync(
|
|
e => e.Name == request.Name && e.City.Guid == request.CityGuid,
|
|
cancellationToken);
|
|
|
|
if (entity != null)
|
|
{
|
|
throw new DuplicateEntityException(
|
|
"Address with given name already exists.");
|
|
}
|
|
|
|
var parentEntity = await _unitOfWork.CityRepository.GetOneAsync(
|
|
e => e.Guid == request.CityGuid, e => e.Region.Country,
|
|
cancellationToken);
|
|
|
|
if (parentEntity == null)
|
|
{
|
|
throw new NotFoundException(
|
|
$"Parent entity with Guid: {request.CityGuid} not found.");
|
|
}
|
|
|
|
entity = new Address()
|
|
{
|
|
Name = request.Name,
|
|
Longitude = request.Longitude,
|
|
Latitude = request.Latitude,
|
|
VehicleType = request.VehicleType,
|
|
CityId = parentEntity.Id
|
|
};
|
|
|
|
entity = await _unitOfWork.AddressRepository.AddOneAsync(
|
|
entity, cancellationToken);
|
|
|
|
await _unitOfWork.SaveAsync(cancellationToken);
|
|
_unitOfWork.Dispose();
|
|
|
|
return _mapper.Map<AddressDto>(entity);
|
|
}
|
|
}
|