public async Task <IActionResult> Put(int id, [FromBody] AuthorRequestDto authReqDto)
        {
            _logger.LogInfo("Updating Author");
            try
            {
                if (authReqDto == null)
                {
                    return(BadRequest("Input data is null"));
                }
                if (!ModelState.IsValid)
                {
                    return(BadRequest("Mandatory fields First Name, Last Name missing"));
                }
                var authDto = _mapper.Map <AuthorDTO>(authReqDto);
                authDto.Id = id;
                var result = await _authorService.Update(_mapper.Map <Author>(authDto));

                _logger.LogInfo($"Author {authDto.FirstName} updated");
                return(Ok($"Updated author {authDto.FirstName} {authDto.LastName} successfully"));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw;
            }
        }
Example #2
0
        public IActionResult Get([FromQuery] AuthorRequestDto authorRequestDto)
        {
            var authorsFromRepo    = _restApiService.GetAuthors(authorRequestDto);
            var paginationMetadata = new
            {
                totalCount  = authorsFromRepo.TotalCount,
                pageSize    = authorsFromRepo.PageSize,
                currentPage = authorsFromRepo.CurrentPage,
                totalPages  = authorsFromRepo.TotalPages,
            };

            Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(paginationMetadata));

            var links          = CreateLinksForAuthors(authorRequestDto, authorsFromRepo.HasNext, authorsFromRepo.HasPrevious);
            var authorToReturn = _mapper.Map <IEnumerable <AuthorDto> >(authorsFromRepo).ShapeData();

            var shapedAuthorsWithLinks = authorToReturn.Select(author =>
            {
                var authorAsDictionary = author as IDictionary <string, object>;
                var authorLinks        = CreateLinksForAuthor((Guid)authorAsDictionary["Id"]);
                authorAsDictionary.Add("links", authorLinks);
                return(authorAsDictionary);
            });

            var linkedCollectionResource = new
            {
                value = shapedAuthorsWithLinks,
                links
            };


            return(Ok(linkedCollectionResource));
        }
        public async Task <IActionResult> Create([FromBody] AuthorRequestDto authReqDto)
        {
            _logger.LogInfo("Creating Author");
            try
            {
                if (authReqDto == null)
                {
                    return(BadRequest("Input data is null"));
                }
                if (!ModelState.IsValid)
                {
                    return(BadRequest("Mandatory fields First Name, Last Name missing"));
                }
                var authDto = _mapper.Map <AuthorDTO>(authReqDto);
                var result  = await _authorService.Create(_mapper.Map <Author>(authDto));

                _logger.LogInfo(result
                    ? $"Author {authReqDto.FirstName} created"
                    : $"Author {authReqDto.FirstName} failed");

                return(Created("Created author successfully", new { authReqDto }));
            }
            catch (Exception ex)
            {
                return(BadRequest(
                           $"Exception Occurred: {ex.Message} {Environment.NewLine} {ex.InnerException} {Environment.NewLine}{ex.StackTrace}"));
            }
        }
Example #4
0
        private string CreateAuthorsResourceUri(AuthorRequestDto authorRequestDto,
                                                ResourceUriType type)
        {
            switch (type)
            {
            case ResourceUriType.PreviousPage:
                return(Url.Link("GetAuthors",
                                new
                {
                    pageNumber = authorRequestDto.PageNumber - 1,
                    pageSize = authorRequestDto.PageSize,
                    searchQuery = authorRequestDto.SearchQuery
                }));

            case ResourceUriType.NextPage:
                return(Url.Link("GetAuthors",
                                new
                {
                    pageNumber = authorRequestDto.PageNumber + 1,
                    pageSize = authorRequestDto.PageSize,
                    searchQuery = authorRequestDto.SearchQuery
                }));

            case ResourceUriType.Current:
            default:
                return(Url.Link("GetAuthors",
                                new
                {
                    pageNumber = authorRequestDto.PageNumber,
                    pageSize = authorRequestDto.PageSize,
                    searchQuery = authorRequestDto.SearchQuery
                }));
            }
        }
Example #5
0
        private IEnumerable <LinkDto> CreateLinksForAuthors(AuthorRequestDto authorRequestDto, bool hasNext, bool hasPrevious)
        {
            var links = new List <LinkDto>
            {
                new LinkDto(CreateAuthorsResourceUri(authorRequestDto, ResourceUriType.Current),
                            "self",
                            "GET")
            };

            if (hasPrevious)
            {
                links.Add(new LinkDto(CreateAuthorsResourceUri(authorRequestDto, ResourceUriType.PreviousPage),
                                      "previousPage",
                                      "GET"));
            }
            if (hasNext)
            {
                links.Add(new LinkDto(CreateAuthorsResourceUri(authorRequestDto, ResourceUriType.NextPage),
                                      "nextPage",
                                      "GET"));
            }


            return(links);
        }
Example #6
0
        public IActionResult FormatAuthorName([FromBody] AuthorRequestDto nameInfo)
        {
            _logger.LogInformation("FormatAuthorName called");
            var formattedName = Author.FormatName(nameInfo.NameString, nameInfo.NameCount);

            return(Ok(RegisterNewAuthorInHistory(nameInfo, formattedName)));
        }
Example #7
0
        private Author RegisterNewAuthorInHistory(AuthorRequestDto nameInfo, string formattedName)
        {
            var newAuthorHistory = new Author()
            {
                NameString = nameInfo.NameString,
                AuthorName = formattedName
            };

            return(_service.RegisterNewAuthorInHistory(newAuthorHistory));
        }
Example #8
0
        private static void SetUpRestApiRepositoryMoq(Mock <IRestApiRepository> restApiRpositoryMoq)
        {
            var authorRequestDto = new AuthorRequestDto();
            var list             = new List <Author>();

            var collection = list.AsQueryable();

            var objectToReturnn = PagedList <Author> .Create(collection, authorRequestDto.PageNumber, authorRequestDto.PageSize);

            restApiRpositoryMoq.Setup(c => c.GetAuthors(It.IsAny <AuthorRequestDto>())).Returns(objectToReturnn);
        }
Example #9
0
        public void given_a_valid_authorId_should_call_repository_once()
        {
            //Arrange
            var authorRequestDto = new AuthorRequestDto();

            // Act on Test
            var response = _restApiService.GetAuthors(authorRequestDto);

            restApiRepositoryMoq.Verify(x => x.GetAuthors(authorRequestDto), Times.Once());

            Assert.IsNotNull(response);
            Assert.IsInstanceOfType(response, typeof(PagedList <Author>));
        }
Example #10
0
        public void given_a_invalid_authorId_should_thow_Agument_Exception()
        {
            //Arrange
            AuthorRequestDto authorRequestDto = null;

            try
            {
                // Act on Test
                _restApiService.GetAuthors(authorRequestDto);
            }
            catch (ArgumentException ex)
            {
                Assert.AreEqual("authorRequestDto", ex.ParamName);
            }
        }