Example #1
0
        public async Task <ActionResult <string> > EditRecipe(RecipeEditDTOin recipe)
        {
            try
            {
                Recipe result = await this.recipeService.EditRecipeAsync(recipe, UserId, IsAdmin);

                if (result != null)
                {
                    return(recipe.Id);
                }
                return(BadRequest(new { reason = "Something went wrong!" }));
            }
            catch (NullReferenceException err)
            {
                return(BadRequest(new { reason = err.Message }));
            }
            catch (InvalidOperationException err)
            {
                return(Unauthorized(new { reason = err.Message }));
            }
        }
Example #2
0
        public async Task <Recipe> EditRecipeAsync(RecipeEditDTOin recipe, string userId, bool isAdmin)
        {
            Recipe recipeFd = await this.recipeRepo.All()
                              .Include(x => x.RecipeIngredients).ThenInclude(i => i.Ingredient)
                              .Include(x => x.RecipeTags).ThenInclude(t => t.Tag)
                              .Include(x => x.Pictures)
                              .FirstOrDefaultAsync(x => x.Id == recipe.Id);

            if (recipeFd is null)
            {
                throw new NullReferenceException("Recipe not found!");
            }
            if (recipeFd.AuthorId != userId && !isAdmin)
            {
                throw new InvalidOperationException("Not allowed to get edit info!");
            }

            var editedRecipe = await MakeRecipe(recipe);

            recipeFd.RecipeIngredients.Clear();
            recipeFd.Pictures.Clear();
            recipeFd.RecipeTags.Clear();
            await recipeRepo.SaveChangesAsync();

            recipeFd.Name        = editedRecipe.Name;
            recipeFd.CategoryId  = editedRecipe.CategoryId;
            recipeFd.Description = editedRecipe.Description;
            recipeFd.VideoLink   = editedRecipe.VideoLink;
            recipeFd.Difficulty  = editedRecipe.Difficulty;
            recipeFd.MainPicture = editedRecipe.MainPicture;

            recipeFd.RecipeIngredients = editedRecipe.RecipeIngredients;
            recipeFd.RecipeTags        = editedRecipe.RecipeTags;
            recipeFd.Pictures          = editedRecipe.Pictures;

            await this.recipeRepo.SaveChangesAsync();

            return(recipeFd);
        }