public async Task <IHttpActionResult> Post(int id, UserRatingsModel userRatings)
        {
            try
            {
                //1. Validate Model State
                if (ModelState.IsValid)
                {
                    List <BeersReviewsModel> results   = new List <BeersReviewsModel>();
                    List <RatingsEntity>     dbRatings = null;

                    //2. Validate if beer exisis in Punk API
                    var beer = await _beerRepository.GetBeer(id);

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

                    //3. If ID exists in Punk API, add rating and save to database.json
                    if (beer.Any())
                    {
                        //4. Read Json and increment Rating Id
                        dbRatings = JsonConvert.DeserializeObject <List <RatingsEntity> >(_jsonUtility.Read("database.json", "Data"));
                        var count = dbRatings?.Max(x => x.Id);
                        count = count == null ? 1 : count + 1;

                        //5. Create Ratings Entity to be saved to json
                        //   Beer ID mapping to user rating request before saving to json
                        var ratings = new RatingsEntity
                        {
                            Id          = count.Value,
                            UserRatings = userRatings,
                            BeerId      = id
                        };

                        //6. Add to json entity
                        dbRatings.Add(ratings);

                        //7. Write and Save to database.json
                        string dbRatingsJson = JsonConvert.SerializeObject(dbRatings);
                        _jsonUtility.Write("database.json", "Data", dbRatingsJson);

                        //8. Return Success with rating info
                        return(Ok(ratings));
                    }
                }
            }
            catch (Exception ex)
            {
                //Return Internal Server Error for unhandled exceptions
                return(InternalServerError(ex));
            }

            //Return Bad Request with error messages for invalid inputs
            return(BadRequest(ModelState));
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Task # 2 - Get top 25 beers matching input string from Punk API along with rating details
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public async Task<IHttpActionResult> Get(string name)//TODO:Add parameter to increase result limit
        {
            try
            {
                //1. Validate Model State
                if (ModelState.IsValid)
                {
                    List<BeersReviewsModel> results = new List<BeersReviewsModel>();
                    List<RatingsEntity> dbRatings = null;

                    //2. Get top 25 beers from Punk API that matches input string
                    var beers = await _beerRepository.GetBeersByName(name);
                    //3. Return Not Found Exception
                    if (beers == null) return NotFound();

                    //4. If Punk API returns results, Add rating details from json
                    if (beers.Any()) 
                    {
                        //5. Get Json ratings
                        dbRatings = JsonConvert.DeserializeObject<List<RatingsEntity>>(_jsonUtility.Read("database.json", "Data"));//Get all ratings

                        //6. Assign ratings for each beer
                        foreach (var beer in beers)
                        {
                            //TODO: Use AutoMapper 
                            results.Add(
                                new BeersReviewsModel
                                {
                                    Id = beer.Id,
                                    Name = beer.Name,
                                    Description = beer.Description,
                                    UserRatings = dbRatings?.Where(x => x.BeerId == beer.Id).Select(x => x.UserRatings).ToList(),
                                });
                        }

                        //7. Return all matching beers with ratings
                        return Ok(results);
                    }
                }
            }
            catch (Exception ex)
            {
                //Return Internal Server Error for unhandled exceptions
                return InternalServerError(ex);
            }

            //Return Bad Request with error messages for invalid inputs
            return BadRequest();
        }