public async Task <ApiResult> Handle(InsertClassifierGroup request, CancellationToken cancellationToken) { if (request.UserUid == Guid.Empty) { throw new InvalidOperationException("User is required."); } var item = request.Item ?? throw new ArgumentNullException(nameof(request.Item)); var type = await _classifierTypeService.Get(request.TypeCode, cancellationToken); using (var scope = _unitOfWorkFactory.Create()) { var itemUid = Guid.NewGuid(); // todo: validation and limits using (var db = _dbContextFactory.Create()) { var tree = await db.GetTable <DbClassifierTree>() .SingleAsync(x => x.TypeUid == type.Uid && x.Uid == request.TreeUid, cancellationToken); var validator = new ClassifierGroupValidator(db); if (await validator.ValidateInsert(item, cancellationToken) == false) { return(new ApiResult { Success = false, Errors = validator.Errors }); } await db.GetTable <DbClassifierGroup>() .Value(x => x.Uid, itemUid) .Value(x => x.TreeUid, tree.Uid) // todo: validate parent belongs to the same tree .Value(x => x.ParentUid, item.ParentUid) .Value(x => x.Code, item.Code) .Value(x => x.Name, item.Name) .InsertAsync(cancellationToken); var closureTable = new ClosureTableHandler(db, type); if (await closureTable.Insert(itemUid, item.ParentUid, cancellationToken) == false) { return(new ApiResult { Success = false, Errors = closureTable.Errors }); } } scope.Commit(); return(new ApiResult { Uid = itemUid }); } }
public async Task <ApiResult> Handle(UpdateClassifierGroup request, CancellationToken cancellationToken) { if (request.UserUid == Guid.Empty) { throw new InvalidOperationException("User is required."); } var item = request.Item ?? throw new ArgumentNullException(nameof(request.Item)); // todo: validate required fields var type = await _classifierTypeService.Get(request.TypeCode, cancellationToken); using (var scope = _unitOfWorkFactory.Create()) { int affected; using (var db = _dbContextFactory.Create()) { /*var tree = await db.GetTable<DbClassifierTree>() * .SingleAsync(x => x.TypeUid == type.Uid && x.Code == request.TreeCode, cancellationToken);*/ var validator = new ClassifierGroupValidator(db); if (await validator.ValidateUpdate(item, cancellationToken) == false) { return(new ApiResult { Success = false, Errors = validator.Errors }); } var closureTable = new ClosureTableHandler(db, type); if (await closureTable.Update(item.Uid, item.ParentUid, cancellationToken) == false) { return(new ApiResult { Success = false, Errors = closureTable.Errors }); } affected = await db.GetTable <DbClassifierGroup>() .Where(x => x.Uid == item.Uid) .Set(x => x.ParentUid, item.ParentUid) .Set(x => x.Code, item.Code) .Set(x => x.Name, item.Name) .UpdateAsync(cancellationToken); } scope.Commit(); return(new ApiResult { AffectedRows = affected }); } }