http-api/src/Application/Buses/Commands/AddBus/AddBusCommandHandler.cs
2025-05-15 19:18:52 +03:00

63 lines
1.8 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.Buses.Commands.AddBus;
public class AddBusCommandHandler :
IRequestHandler<AddBusCommand, BusDto>
{
private readonly UnitOfWork _unitOfWork;
private readonly IMapper _mapper;
public AddBusCommandHandler(
UnitOfWork unitOfWork,
IMapper mapper)
{
_unitOfWork = unitOfWork;
_mapper = mapper;
}
public async Task<BusDto> Handle(
AddBusCommand request,
CancellationToken cancellationToken)
{
var entity = await _unitOfWork.BusRepository.GetOneAsync(
e => e.Number == request.Number, cancellationToken);
if (entity != 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 = new Bus()
{
Number = request.Number,
Model = request.Model,
Capacity = request.Capacity,
CompanyId = parentEntity.Id,
Company = parentEntity
};
entity = await _unitOfWork.BusRepository.AddOneAsync(
entity, cancellationToken);
await _unitOfWork.SaveAsync(cancellationToken);
_unitOfWork.Dispose();
return _mapper.Map<BusDto>(entity);
}
}