Ejemplo n.º 1
0
        public ActionResult <IEnumerable <AuhtorDTO> > GetAuthors([FromQuery] AuhtorResourceParameters auhtorResourceParameters)
        {
            try
            {
                var GetAllAuthors = _courseLibrary.GetAuthors(auhtorResourceParameters);

                //checking if there is a previous link, if there is calle dthe method, if not set to null
                var previousPageLink = GetAllAuthors.HasPrevious ? CreateAuthorsResourceUris(auhtorResourceParameters, ResourceUriType.PreviousPage) : null;

                var nextPageLink = GetAllAuthors.HasNext ? CreateAuthorsResourceUris(auhtorResourceParameters, ResourceUriType.NextPage) : null;

                //then we create the MetaData we want to return to the user for guide

                var paginationMetaData = new
                {
                    totalCount  = GetAllAuthors.Totalcount,
                    pageSize    = GetAllAuthors.PageSize,
                    currentPage = GetAllAuthors.CurrentPage,
                    previousPageLink,
                    nextPageLink
                };

                //Adding to the header
                Response.Headers.Add("X-Pagination", JsonSerializer.Serialize(paginationMetaData));


                //using Automapper for cleaner code instead of select Query,(seee below)
                //the return type first(destination), then the source
                var auhtors = _mapper.Map <IEnumerable <AuhtorDTO> >(GetAllAuthors);

                //var auhtors = GetAllAuthors
                //    .Select(a => new AuhtorDTO
                //    {
                //        ID = a.ID,
                //        Name =$"{a.FirstName} {a.LastName}",
                //        //An extention method written to grab the Authors age
                //        Age = DateTimeOffSetExtensions.GetCurrentAge(a.DateOfBirth),
                //        MainCategory = a.MainCategory,
                //        Courses = a.Courses,
                //    });


                // return body format for the Api with right statusCode
                return(Ok(new JsonResponse <AuhtorDTO>()
                {
                    Success = true,
                    Results = auhtors
                }));
            }

            catch (Exception ex)
            {
                //log ex
                var path         = HttpContext.Request.Path;
                var query        = HttpContext.Request.QueryString;
                var pathAndQuery = path + query;
                var messg        = _courseLibrary.LogErrorMessage(ex.Message, pathAndQuery);
                return(Ok(new JsonResponse <string>()
                {
                    Success = false,
                    ErrorMessage = "Sorry, something just went wrong while processing your request! Pls Try Again."
                }));


                //return StatusCode(500, messg);
            }

            // return Ok(GetAllAuthors);
        }