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

31 lines
1.3 KiB
C#

namespace Brizco.Repository.Handlers.Routines;
public class CreateRoutineCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
: IRequestHandler<CreateRoutineCommand, RoutineSDto>
{
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;
}
}
}