Esempio n. 1
0
        public async Task <IActionResult> AddMealIngredient([FromBody] MealIngredientCreationVM mealIngredientCreationVM)
        {
            if (!ModelState.IsValid)
            {
                return(NotFound());
            }

            var userId = new Guid(User.Identity.Name);

            var mealIngredient = await _mealIngredientService.AddMealIngredientAsync(userId, mealIngredientCreationVM);

            return(Ok(mealIngredient));
        }
        public async Task <Guid> AddMealIngredientAsync(Guid userId, MealIngredientCreationVM mealIngredient)
        {
            ValidateArgument(mealIngredient, nameof(mealIngredient));

            var dbMealIngredient = _mapper.Map <MealIngredient>(mealIngredient);

            dbMealIngredient.CreatorId = userId;

            bool mealIngredientNutritionsAddedSuccessfully = await _mealIngredientRepository.AddMealIngredientNutritionsAsync(dbMealIngredient.Nutrition);

            if (!mealIngredientNutritionsAddedSuccessfully)
            {
                throw new DataAccessException("Failed adding nutritions: " + JsonConvert.SerializeObject(dbMealIngredient.Nutrition) + "for mealIngredient: "
                                              + JsonConvert.SerializeObject(dbMealIngredient));
            }

            dbMealIngredient.NutritionsId = dbMealIngredient.Nutrition.Id;

            bool mealIngredientAddedSuccesfully = await _mealIngredientRepository.AddAsync(dbMealIngredient);

            if (!mealIngredientAddedSuccesfully)
            {
                throw new DataAccessException("MealIngredient couldn't be added. MealIngredient:" + JsonConvert.SerializeObject(dbMealIngredient));
            }

            await _userRepository.IncrementCreatedMealIngredientsCountAsync(userId);

            var logNewMealIngredientAddedTask = _activityService.LogNewMealIngredientAddedAsync(userId, dbMealIngredient.Id);
            var userTask = _userRepository.GetUserByIdAsync(userId);

            await Task.WhenAll(userTask, logNewMealIngredientAddedTask);

            await _achievementService.CheckForNumberOfMealIngredientAdditionsByUserAsync(userTask.Result);

            return(dbMealIngredient.Id);
        }