예제 #1
0
        public ActionResult <BrewDto> CreateBrew([FromBody] BrewForCreationDto brew,
                                                 [FromHeader(Name = ExtendedControllerBase.ACCEPT)] string mediaTypes)
        {
            var splitMediaTypes = mediaTypes.Split(',');

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

            if (!_homebrewRepository.RecipeExists(brew.RecipeId))
            {
                ModelState.AddModelError(
                    "Recipe ID",
                    $"The associated recipe id [{brew.RecipeId}] for the {brew.Name} brew must be valid.");
            }

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

            var includeSteps          = true;
            var includeAdditionalInfo = true;
            var finalBrew             = _mapper.Map <Entities.Brew>(brew);

            _homebrewRepository.AddBrew(finalBrew);
            finalBrew.Recipe = _homebrewRepository.GetRecipe(brew.RecipeId, includeSteps);
            _homebrewRepository.Save();

            var brewToReturn = _mapper.Map <Models.BrewDto>(finalBrew);

            if (parsedMediaTypes.Any(pmt => pmt.SubTypeWithoutSuffix.EndsWith(this.HATEOAS, StringComparison.InvariantCultureIgnoreCase)))
            {
                var links = CreateLinksForBrew(brewToReturn.Id, includeAdditionalInfo);

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

                linkedResourceToReturn.Add(this.LINKS, links);

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

            return(CreatedAtRoute(
                       "GetBrew",
                       new { id = brewToReturn.Id, includeAdditionalInfo },
                       brewToReturn));
        }