Ejemplo n.º 1
0
        public async Task <IActionResult> PostAsync([FromBody] RecipeInputResource resource)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState.GetErrorMessages()));
            }

            var result = await this.recipesService.AddAsync(resource);

            if (!result.Success)
            {
                return(BadRequest(result.Message));
            }

            return(Ok(result.Recipe));
        }
Ejemplo n.º 2
0
        public async Task <RecipeResponse> AddAsync(RecipeInputResource resource)
        {
            var currentRecipe = new Recipe
            {
                ImageUrl     = resource.ImageUrl,
                Name         = resource.Name,
                Instructions = resource.Instructions,
                CookingTime  = TimeSpan.FromMinutes(resource.CookingTime)
            };

            var category = await this.categoriesRepository.GetByNameAsync(resource.Category);

            if (category == null)
            {
                category = new Category()
                {
                    Name = resource.Category,
                };
            }

            currentRecipe.Category = category;

            foreach (var recipeIngredient in resource.Ingredients)
            {
                var currentIngredient = await this.ingredientsRepository.GetByNameAsync(recipeIngredient.Name);

                if (currentIngredient == null)
                {
                    currentIngredient = new Ingredient()
                    {
                        Name = recipeIngredient.Name,
                    };
                }

                UnitOfMeasurement measurment;

                var isEnumParsed = Enum.TryParse(recipeIngredient.IngredientMeasurement, true, out measurment);

                if (!isEnumParsed)
                {
                    return(new RecipeResponse(string.Format(GlobalConstants.WrongRecipeIngredientMeasurmentMessage, recipeIngredient.Name)));
                }

                var currentRecipeIngredient = new RecipeIngredient()
                {
                    Ingredient            = currentIngredient,
                    Recipe                = currentRecipe,
                    Quantity              = recipeIngredient.Quantity,
                    IngredientMeasurement = measurment,
                };

                currentRecipe.RecipeIngredients.Add(currentRecipeIngredient);
            }

            try
            {
                await this.recipeRepository.AddAsync(currentRecipe);

                var recipeResourse = this.mapper.Map <Recipe, RecipeByIdResource>(currentRecipe);

                return(new RecipeResponse(recipeResourse));
            }
            catch (Exception ex)
            {
                //TODO: Log errors

                return(new RecipeResponse(string.Format(GlobalConstants.AddRecipeErrorMessage, ex.Message)));
            }
        }