Api/Brizco.Repository/Handlers/Routine/CreateRoutineCommandHandler.cs

38 lines
1.5 KiB
C#

namespace Brizco.Repository.Handlers.Routine;
public class CreateRoutineCommandHandler : IRequestHandler<CreateRoutineCommand, RoutineSDto>
{
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ICurrentUserService _currentUserService;
public CreateRoutineCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
{
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
}
public async Task<RoutineSDto> Handle(CreateRoutineCommand request, CancellationToken cancellationToken)
{
if (_currentUserService.ComplexId == null)
throw new AppException("ComplexId is null", ApiResultStatusCode.NotFound);
if (!Guid.TryParse(_currentUserService.ComplexId, out Guid complexId))
throw new AppException("ComplexId is wrong", ApiResultStatusCode.NotFound);
try
{
await _repositoryWrapper.BeginTransaction(cancellationToken);
var entity = Domain.Entities.Routines.Routine
.Create(request.Name,request.Description,complexId);
_repositoryWrapper.SetRepository<Domain.Entities.Routines.Routine>().Add(entity);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
await _repositoryWrapper.CommitAsync(cancellationToken);
return entity.AdaptToSDto();
}
catch (Exception)
{
await _repositoryWrapper.RollBackAsync(cancellationToken);
throw;
}
}
}