Exemplo n.º 1
0
        public async Task <ActionResult> Update(Guid id, RateUpdateDto updateDto)
        {
            if (id != updateDto.Id)
            {
                return(UnprocessableEntity("Url id must match update id"));
            }

            var user = await _GetAuthUser();

            // should never happens, only if [Authorize] is removed
            if (user == null)
            {
                return(Unauthorized());
            }

            var newRate = _mapper.Map <RateEntity>(updateDto);

            newRate.UserId = user.Id;


            try
            {
                // get rate before update because we need oldVote to updateRate of relative boardGame
                var oldRate = await _rateRepository.GetById(newRate.Id);

                if (user.Id != oldRate.UserId)
                {
                    return(Forbid("this Rate cannot be update by a different User"));
                }

                await TX.Run(async() =>
                {
                    await _rateRepository.Patch(oldRate, newRate);

                    var boardGame = await _boardGameRepository.GetById(newRate.BoardGameId);
                    await _boardGameRepository.UpdateRate(boardGame, oldRate.Vote, newRate.Vote);
                });

                return(Ok());
            }
            catch (Exception exception)
            {
                if (exception is RecordNotFoundException)
                {
                    return(BadRequest(exception.Message));
                }

                if (exception is UniqueException)
                {
                    return(Conflict(exception.Message));
                }

                throw;
            }
        }