Пример #1
0
        public async Task <IActionResult> CreateRecipe(
            [ModelBinder(typeof(JsonWithFilesFormDataModelBinder), Name = "recipe")][FromForm] RecipeForCreationDto recipe,
            [FromForm] IFormFile file)
        {
            if (recipe == null)
            {
                return(BadRequest("RecipeForCreationDto object is null"));
            }

            if (!ModelState.IsValid)
            {
                return(UnprocessableEntity(ModelState));
            }

            var photoPath = _photoService.UploadFile(file);

            var recipeEntity = _mapper.Map <Recipe>(recipe);

            recipeEntity.PhotoPath = photoPath;

            _repository.Recipe.CreateRecipe(recipeEntity);
            await _repository.SaveAsync();

            var recipeToReturn = _mapper.Map <RecipeDto>(recipeEntity);

            return(CreatedAtRoute("RecipeById", new { id = recipeToReturn.Id }, recipeToReturn));
        }
Пример #2
0
        public async Task <IActionResult> UpdateRecipe(
            [FromForm] Guid id, [ModelBinder(typeof(JsonWithFilesFormDataModelBinder), Name = "recipe")][FromForm] RecipeForCreationDto recipe,
            [FromForm] IFormFile file)
        {
            if (recipe == null)
            {
                return(BadRequest("RecipeForUpdateDto object is null"));
            }

            if (!ModelState.IsValid)
            {
                return(UnprocessableEntity(ModelState));
            }

            var recipeEntity = await _repository.Recipe.GetRecipeAsync(id, trackChanges : true);

            if (recipeEntity == null)
            {
                return(NotFound());
            }

            var oldPhotoPath = recipeEntity.PhotoPath;

            _photoService.DeletePhoto(oldPhotoPath);

            var photoPath = _photoService.UploadFile(file);

            _mapper.Map(recipe, recipeEntity);

            recipeEntity.PhotoPath = photoPath;

            await _repository.SaveAsync();

            return(NoContent());
        }
        public ActionResult <RecipeDto> CreateRecipe([FromBody] RecipeForCreationDto recipe,
                                                     [FromHeader(Name = ExtendedControllerBase.ACCEPT)] string mediaTypes)
        {
            var splitMediaTypes = mediaTypes.Split(',');

            if (!MediaTypeHeaderValue.TryParseList(splitMediaTypes,
                                                   out IList <MediaTypeHeaderValue> parsedMediaTypes))
            {
                return(BadRequest());
            }

            if (!_homeBrewRepository.WaterProfileExists(recipe.WaterProfileId))
            {
                ModelState.AddModelError(
                    "Description",
                    "The water profile ID for the recipe must exist.");
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var includeSteps = true;
            var finalRecipe  = _mapper.Map <Entities.Recipe>(recipe);

            _homeBrewRepository.AddRecipe(finalRecipe);
            finalRecipe.WaterProfile = _homeBrewRepository.GetWaterProfile(recipe.WaterProfileId, true);
            _homeBrewRepository.Save();

            var recipeToReturn = _mapper.Map <Models.RecipeDto>(finalRecipe);

            if (parsedMediaTypes.Any(pmt => pmt.SubTypeWithoutSuffix.EndsWith(this.HATEOAS, StringComparison.InvariantCultureIgnoreCase)))
            {
                var links = CreateLinksForRecipe(recipeToReturn.Id, includeSteps);

                var linkedResourceToReturn = recipeToReturn.ShapeData(null)
                                             as IDictionary <string, object>;

                linkedResourceToReturn.Add(this.LINKS, links);

                return(CreatedAtRoute(
                           "GetRecipe",
                           new { id = linkedResourceToReturn["Id"], includeSteps },
                           linkedResourceToReturn));
            }

            return(CreatedAtRoute(
                       "GetRecipe",
                       new { id = recipeToReturn.Id, includeSteps },
                       recipeToReturn));
        }
Пример #4
0
        public ActionResult <RecipeDto> AddRecipe(RecipeForCreationDto recipeForCreation)
        {
            var recipe = _mapper.Map <Recipe>(recipeForCreation);

            _recipeRepository.AddRecipe(recipe);
            _recipeRepository.Save();

            var recipeDto = _mapper.Map <RecipeDto>(recipe);

            return(CreatedAtRoute("GetRecipe",
                                  new { recipeDto.RecipeId },
                                  recipeDto));
        }
Пример #5
0
        public IActionResult CreateRecipe([FromBody] RecipeForCreationDto recipeForCreation)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var recipeDto     = mapper.Map <RecipeDto>(recipeForCreation);
            var idOfNewRecipe = recipesService.InsertRecipe(recipeDto);

            if (idOfNewRecipe > 0)
            {
                recipeDto.Id = idOfNewRecipe;
                return(CreatedAtRoute("GetRecipe", new { Id = idOfNewRecipe }, recipeDto));
            }
            else
            {
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
        }
Пример #6
0
        public void CreateRecipe_WithTitleAndInstructions_ReturnsCreatedResult()
        {
            // Arrange
            recipesServiceMock = new Mock <IRecipesService>();
            recipesServiceMock
            .Setup(m => m.InsertRecipe(It.IsAny <RecipeDto>()))
            .Returns(1);
            recipesController = new RecipesController(recipesServiceMock.Object, mapper);

            var recipeForCreation = new RecipeForCreationDto
            {
                Title       = "Cooking is fun",
                Instruction = "You should cook the meal"
            };

            // Act
            var result = recipesController.CreateRecipe(recipeForCreation);

            // Assert
            Assert.IsTrue(result.GetType() == typeof(CreatedAtRouteResult));
        }
Пример #7
0
        public void CreateRecipe_SomethinWentWrongWhileInserting_Returns500InternalServerError()
        {
            // Arrange
            recipesServiceMock = new Mock <IRecipesService>();
            recipesServiceMock
            .Setup(m => m.InsertRecipe(It.IsAny <RecipeDto>()))
            .Returns(0);
            recipesController = new RecipesController(recipesServiceMock.Object, mapper);

            var recipeForCreation = new RecipeForCreationDto
            {
                Title       = "Cooking is fun",
                Instruction = "You should cook the meal"
            };

            // Act
            var result = recipesController.CreateRecipe(recipeForCreation);

            // Assert
            Assert.IsTrue(result.GetType() == typeof(StatusCodeResult));
            Assert.IsTrue(((StatusCodeResult)result).StatusCode == StatusCodes.Status500InternalServerError);
        }
Пример #8
0
        public ActionResult <RecipeDto> AddRecipe(RecipeForCreationDto recipeForCreation)
        {
            var validationResults = new RecipeForCreationDtoValidator().Validate(recipeForCreation);

            validationResults.AddToModelState(ModelState, null);

            if (!ModelState.IsValid)
            {
                return(BadRequest(new ValidationProblemDetails(ModelState)));
                //return ValidationProblem();
            }

            var recipe = _mapper.Map <Recipe>(recipeForCreation);

            _recipeRepository.AddRecipe(recipe);
            _recipeRepository.Save();

            var recipeDto = _mapper.Map <RecipeDto>(recipe);

            return(CreatedAtRoute("GetRecipe",
                                  new { recipeDto.RecipeId },
                                  recipeDto));
        }
Пример #9
0
        public IActionResult CreateRecipe(int categoryId,
                                          [FromBody] RecipeForCreationDto recipe)
        {
            if (recipe == null)
            {
                return(BadRequest());
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var category = RecipesDataStore.Current.Categories.FirstOrDefault(c => c.Id == categoryId);

            if (category == null)
            {
                return(NotFound());
            }

            var maxrecipeId = RecipesDataStore.Current.Categories.SelectMany(
                c => c.Recipes).Max(r => r.Id);

            var finalRecipe = new Recipe()
            {
                Id          = ++maxrecipeId,
                Name        = recipe.Name,
                Description = recipe.Description,
                Ingedients  = recipe.Ingedients,
                Preparation = recipe.Preparation
            };

            category.Recipes.Add(finalRecipe);
            return(CreatedAtRoute("GetRecipesForCategory", new
                                  { category = categoryId, id = finalRecipe.Id }, finalRecipe));
        }
Пример #10
0
        public IActionResult CreateRecipe([FromBody] RecipeForCreationDto recipeDto)
        {
            if (recipeDto == null)
            {
                return(StatusCode(400, "Wrong JSON object."));
            }

            if (recipeDto.Categories.Count() < 1)
            {
                ModelState.AddModelError(nameof(RecipeForCreationDto),
                                         "You should fill out at least one category.");
            }

            if (recipeDto.Ingredients.Count() < 1)
            {
                ModelState.AddModelError(nameof(RecipeForCreationDto),
                                         "You should fill out at least one ingredient.");
            }

            if (String.IsNullOrEmpty(recipeDto.Directions.Step))
            {
                ModelState.AddModelError(nameof(RecipeForCreationDto),
                                         "You should fill out direction step.");
            }

            if (!ModelState.IsValid)
            {
                return(new UnprocessableEntityObjectResult(ModelState));
            }

            if (_recipeRepository.RecipeExist(recipeDto.Title))
            {
                return(StatusCode(409, "Recipe duplicated."));
            }

            var recipeEntity = Mapper.Map <Recipe>(recipeDto);

            foreach (var categoryName in recipeDto.Categories)
            {
                var recipeCategory = new RecipeCategory();
                var category       = _recipeRepository.GetCategory(categoryName);

                if (category == null)
                {
                    recipeCategory.Category = new Category()
                    {
                        CategoryId = Guid.NewGuid(),
                        Name       = categoryName
                    };
                }
                else
                {
                    recipeCategory.Category = category;
                }
                recipeEntity.RecipeCategories.Add(recipeCategory);
            }

            _recipeRepository.AddRecipe(recipeEntity);

            if (!_recipeRepository.Save())
            {
                return(StatusCode(500, "Internal error occured."));
            }

            var recipeToReturn = Mapper.Map <RecipeDto>(recipeEntity);

            return(CreatedAtRoute("GetRecipes", null, recipeToReturn));
        }