Esempio n. 1
0
        public async Task<IActionResult> AddBook([FromForm]BookForCreationDto bookForCreationDto)
        {
            //bookForCreationDto.Title = bookForCreationDto.Title.ToLower();

            if (await _repo.BookExists(bookForCreationDto.Title))
                return BadRequest("Book Name already Exist");

            var file = bookForCreationDto.File;
            var uploadResult = new ImageUploadResult();

            if(file.Length > 0)
            {
                using(var stream = file.OpenReadStream())
                {
                    var uploadParams = new ImageUploadParams()
                    {
                        File = new FileDescription(file.Name, stream),
                        Transformation = new Transformation()
                        .Width(500).Height(500).Crop("fill").Gravity("face")
                    };

                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }
            bookForCreationDto.PhotoUrl = uploadResult.Uri.ToString();
            bookForCreationDto.PublicId = uploadResult.PublicId;
            //var userToCreate = new User { Username = userForRegisterDto.Username };
            var bookToCreate = _mapper.Map<Book>(bookForCreationDto);

            var createdbook = await _repo.AddBook(bookToCreate);

            return CreatedAtRoute("GetBook", new{Controller = "book", id =createdbook.Id}, createdbook);
        }
Esempio n. 2
0
        public async Task <IActionResult> AddBook(int userId,
                                                  [FromForm] BookForCreationDto bookForCreationDto)
        {
            //Checking if the userId matches the currently logged in User's ID
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            var userFromRepo = await _repo.GetUser(userId);

            if (userFromRepo != null)
            {
                //Adding the Book to the User's library and to the database
                var book = _mapper.Map <Book>(bookForCreationDto);
                var read = new Read();
                read.Book = book;
                read.User = userFromRepo;

                _repo.Add(book);
                _repo.Add(read);
                //Uploading the Book's picture to the cloud
                _repo.UploadPictureToCloud(book, bookForCreationDto.File);

                //Saving changes
                if (await _repo.SaveAll())
                {
                    var bookToReturn = _mapper.Map <BookDetailedViewDto>(book);
                    return(CreatedAtRoute("GetBookDetail", new { bookId = book.Id }, bookToReturn));
                }
            }
            //if the User was not found
            return(BadRequest("Could not add the book"));
        }
Esempio n. 3
0
        public IActionResult CreateBookForAuthor(Guid authorId, [FromBody] BookForCreationDto dto)
        {
            if (dto == null)
            {
                return(BadRequest());
            }

            if (!libraryRepository.AuthorExists(authorId))
            {
                return(NotFound());
            }

            var bookEntity = Mapper.Map <Book>(dto);

            libraryRepository.AddBookForAuthor(authorId, bookEntity);

            if (!libraryRepository.Save())
            {
                throw new Exception($"Creating a book for author {authorId} failed on save");
            }

            var bookToReturn = Mapper.Map <BookDto>(bookEntity);

            return(CreatedAtAction(
                       nameof(GetBookForAuthor),
                       new { authorId, id = bookToReturn.Id },
                       bookToReturn
                       ));
        }
Esempio n. 4
0
        public IActionResult CreateBookForAuthor(Guid authorId, [FromBody] BookForCreationDto book)
        {
            if (book == null)
            {
                return(BadRequest());
            }

            if (book.Description == book.Title)
            {
                ModelState.AddModelError(nameof(BookForCreationDto),
                                         "Description debe ser diferente de Title");
            }

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

            if (!_libraryRepository.AuthorExists(authorId))
            {
                return(NotFound());
            }

            var bookEntity = AutoMapper.Mapper.Map <Entities.Book>(book);

            _libraryRepository.AddBookForAuthor(authorId, bookEntity);
            if (!_libraryRepository.Save())
            {
                throw new Exception($"Creating a book for {authorId} failed on save");
            }

            var bookToReturn = AutoMapper.Mapper.Map <Models.BookDto>(bookEntity);

            return(CreatedAtRoute("GetBookForAuthor", new { id = bookToReturn.Id }, bookToReturn));
        }
Esempio n. 5
0
        public IActionResult CreateBookForAuthor(Guid authorId, [FromBody] BookForCreationDto book)
        {
            if (book == null)
            {
                return(BadRequest());
            }
            //custom validation logic
            if (book.Description == book.Title)
            {
                ModelState.AddModelError(nameof(BookForCreationDto), "Descript and Title must be different");
            }
            //validation
            if (!ModelState.IsValid)
            {
                return(new UnprocessableEntityObjectResult(ModelState)); //422
            }
            if (!_libraryRepository.AuthorExists(authorId))
            {
                return(NotFound());
            }

            var bookEntity = book.ConvertToBookEntity();

            _libraryRepository.AddBookForAuthor(authorId, bookEntity);
            _libraryRepository.Save();
            var bookToReturn = bookEntity.ConvertToBookDto();

            //return CreatedAtRoute("GetBook", new {authorId = bookToReturn.AuthorId, id = bookToReturn.Id }, bookToReturn);
            return(CreatedAtRoute("GetBook", new { authorId = bookToReturn.AuthorId, id = bookToReturn.Id }, CreateLinksForBook(bookToReturn)));
        }
Esempio n. 6
0
        public IActionResult CreateBookForAuthor(Guid authorId,
                                                 [FromBody] BookForCreationDto bookDto)
        {
            if (bookDto == null)
            {
                return(BadRequest());
            }

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

            if (!_repository.AuthorExists(authorId))
            {
                return(NotFound());
            }

            var entity = Mapper.Map <Book>(bookDto);

            _repository.AddBookForAuthor(authorId, entity);

            if (!_repository.Save())
            {
                throw new Exception("Failed on creating this book.");
            }

            var bookToReturn = Mapper.Map <BookDto>(entity);

            return(CreatedAtRoute("GetBook",
                                  new { authorId = bookToReturn.AuthorId, id = bookToReturn.Id },
                                  CreateLinksForBook(bookToReturn)));
        }
Esempio n. 7
0
        public IActionResult CreateBookForAuthor(Guid authorId, [FromBody] BookForCreationDto book)
        {
            if (book == null)
            {
                return(BadRequest());
            }

            CheckForAdditionalModelValidationsForBook(book);
            if (!ModelState.IsValid)
            {
                return(new UnprocessibleEntityObjectResult(ModelState));
            }

            if (!_libraryRepository.AuthorExists(authorId))
            {
                return(NotFound());
            }

            var bookEntity = AutoMapper.Mapper.Map <Book>(book);

            _libraryRepository.AddBookForAuthor(authorId, bookEntity);
            if (!_libraryRepository.Save())
            {
                throw new Exception("Creating a book faild at saving to database.");
            }

            var bookToReturn = AutoMapper.Mapper.Map <BookDto>(bookEntity);

            return(CreatedAtRoute("GetBookForAuthor", new { authorId = authorId, bookId = bookToReturn.Id }, bookToReturn));
        }
Esempio n. 8
0
        public IActionResult CreateBookForAuthor(Guid authorId, [FromBody] BookForCreationDto book)
        {
            if (book == null)
            {
                return(BadRequest());
            }

            if (!_libraryRepository.AuthorExists(authorId))
            {
                return(NotFound());
            }

            var bookEntity = Mapper.Map <Book>(book);

            _libraryRepository.AddBookForAuthor(authorId, bookEntity);

            if (!_libraryRepository.Save())
            {
                throw  new Exception($"Creating a book for author {authorId} failed to save");
            }

            var bookToReturn = Mapper.Map <BookDto>(bookEntity);

            //Notice the bookToReturn (newly created book) at the end. It is required as this is
            //going to be seralised into request body
            return(CreatedAtRoute("GetBookForAuthor",
                                  new { authorId = authorId, id = bookToReturn.Id }, bookToReturn));
        }
Esempio n. 9
0
        public ActionResult <BookDto> CreateBook(BookForCreationDto book)
        {
            var bookEntity = _mapper.Map <Book>(book);

            if (!TryValidateModel(bookEntity))
            {
                return(ValidationProblem(ModelState));
            }

            _repositoryWrapper.Books.Add(bookEntity);

            foreach (var author in book.Authors)
            {
                var authorEntity = _mapper.Map <Author>(author);
                _repositoryWrapper.Authors.Add(authorEntity);

                BookAuthor bookAuthorEntity = new BookAuthor()
                {
                    BookId   = bookEntity.BookId,
                    Book     = bookEntity,
                    AuthorId = authorEntity.AuthorId,
                    Author   = authorEntity
                };
                _repositoryWrapper.BookAuthors.Add(bookAuthorEntity);
            }

            var bookToReturn = _mapper.Map <BookDto>(bookEntity);

            return(CreatedAtRoute("GetBook",
                                  new { bookId = bookToReturn.BookId },
                                  bookToReturn));
        }
        public async Task CreateBookForAuthorAsync_ThrowException_Test()
        {
            // Arrange
            var mapper = new MapperConfiguration(cfg => cfg.AddProfile(new BookProfile())).CreateMapper();

            var authorId           = Guid.Parse("a1da1d8e-1988-4634-b538-a01709477b77");
            var bookForCreationDto = new BookForCreationDto {
                Title = "The Book", Description = "The Description..."
            };
            var bookEntity = mapper.Map <Book>(bookForCreationDto);

            var mockRepo = new Mock <ILibraryRepository>();

            mockRepo.Setup(repo => repo.AuthorExistsAsync(authorId))
            .ReturnsAsync(true);
            mockRepo.Setup(repo => repo.AddBookForAuthorAsync(authorId, bookEntity))
            .Returns(Task.CompletedTask);
            mockRepo.Setup(repo => repo.SaveChangesAsync())
            .ReturnsAsync(false);
            var controller = new BooksController(mockRepo.Object, mapper);

            // Act
            var result = await Assert.ThrowsAsync <Exception>(() => controller.CreateBookForAuthorAsync(authorId, book: bookForCreationDto));

            // Assert
            Assert.Equal($"Creating a book for author {authorId} failed on save.", result.Message);
        }
Esempio n. 11
0
        public IActionResult CreateBookForAuthor(Guid authorId, [FromBody] BookForCreationDto book)
        {
            if (book == null)
            {
                return(BadRequest());
            }

            if (!_libraryRepository.AuthorExists(authorId))
            {
                return(NotFound());
            }

            var bookEntity = Mapper.Map <Book> (book);

            _libraryRepository.AddBookForAuthor(authorId, bookEntity);

            if (!_libraryRepository.Save())
            {
                throw new Exception($"Fail to create book for {authorId}");
            }

            var bookToReturn = Mapper.Map <BookDto> (bookEntity);

            // create a uri in returned header, the parameters must be exact with GetBookByAuthor
            // otherwise it won't work
            return(CreatedAtRoute("GetBook4Author", new { authorId = authorId, bookId = bookToReturn.Id }, bookToReturn));
        }
        public async Task CreateBookForAuthorAsync_Test()
        {
            // Arrange
            var mapper = new MapperConfiguration(cfg => cfg.AddProfile(new BookProfile())).CreateMapper();

            var authorId           = Guid.Parse("a1da1d8e-1988-4634-b538-a01709477b77");
            var bookForCreationDto = new BookForCreationDto {
                Title = "The Book", Description = "The Description..."
            };
            var bookEntity = mapper.Map <Book>(bookForCreationDto);

            var mockRepo = new Mock <ILibraryRepository>();

            mockRepo.Setup(repo => repo.AuthorExistsAsync(authorId))
            .ReturnsAsync(true);
            mockRepo.Setup(repo => repo.AddBookForAuthorAsync(authorId, bookEntity))
            .Returns(Task.CompletedTask);
            mockRepo.Setup(repo => repo.SaveChangesAsync())
            .ReturnsAsync(true);
            var controller = new BooksController(mockRepo.Object, mapper);

            // Act
            var result = await controller.CreateBookForAuthorAsync(authorId, book : bookForCreationDto);

            // Assert
            var actionResult = Assert.IsType <ActionResult <BookDto> >(result);

            Assert.IsType <CreatedAtRouteResult>(actionResult.Result);
        }
Esempio n. 13
0
        public IActionResult CreateBookForAuthor(Guid authorId,
                                                 [FromBody] BookForCreationDto book)
        {
            if (book == null)
            {
                return(BadRequest());
            }

            if (!_libraryRepository.AuthorExists(authorId))
            {
                return(NotFound());
            }

            var bookEntity = Mapper.Map <Book>(book);

            _libraryRepository.AddBookForAuthor(authorId, bookEntity);

            if (!_libraryRepository.Save())
            {
                throw new Exception($"Fallo la creacion del libreo para el autor {authorId} durante la grabación");
            }

            var bookToReturn = Mapper.Map <BookDto>(bookEntity);

            return(CreatedAtRoute("GetBookForAuthor",
                                  new { authorId = authorId, id = bookToReturn.Id },
                                  bookToReturn));
        }
Esempio n. 14
0
        public IActionResult CreateBookForAuthor(Guid authorId,
                                                 [FromBody] BookForCreationDto book)
        {
            if (book == null)
            {
                return(BadRequest());
            }

            if (!_libraryRepository.AuthorExists(authorId))
            {
                return(NotFound());
            }

            var bookEntity = Mapper.Map <Book>(book);

            _libraryRepository.AddBookForAuthor(authorId, bookEntity);

            if (!_libraryRepository.Save())
            {
                throw new Exception($"Creating a book for author {authorId} failed on save.");
            }

            var bookToReturn = Mapper.Map <BookDto>(bookEntity);

            return(CreatedAtRoute("GetBookForAuthor",
                                  new { authorId, id = bookToReturn.Id },
                                  CreateLinksForBook(bookToReturn)));
        }
Esempio n. 15
0
        public IActionResult Post(Guid authorId, [FromBody] BookForCreationDto book)
        {
            if (book == null)
            {
                return(BadRequest( ));
            }
            if (book.Title == book.Description)
            {
                ModelState.AddModelError(nameof(BookForCreationDto), "Title & Description should be different.");
            }
            if (!ModelState.IsValid)
            {
                return(new UnprocessableEntityObjectResult(ModelState));
            }
            if (!_repo.AuthorExists(authorId))
            {
                return(BadRequest( ));
            }

            var bookEntity = Mapper.Map <Book>(book);

            _repo.AddBookForAuthor(authorId, bookEntity);
            if (!_repo.Save( ))
            {
                throw new Exception($"Creating book failed for {authorId}");
            }
            var bookToReturn = Mapper.Map <BookDto>(bookEntity);

            return(CreatedAtRoute("GetBookForAuthor",
                                  new { authorId = authorId, id = bookEntity.Id }, CreateLinksForBook(bookToReturn)));
        }
Esempio n. 16
0
        public IActionResult CreateBookForAuthor(Guid authorId,
                                                 [FromBody] BookForCreationDto book)
        {
            if (book == null)
            {
                return(BadRequest());
            }

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

            if (!libraryRepository.AuthorExists(authorId))
            {
                return(NotFound());
            }

            var bookEntity = Mapper.Map <Book>(book);

            libraryRepository.AddBookForAuthor(authorId, bookEntity);

            if (!libraryRepository.Save())
            {
                throw new Exception($"Creating a book for author {authorId} failed on save.");
            }

            var bookToReturn = Mapper.Map <BookDto>(bookEntity);

            return(CreatedAtRoute("GetBookForAuthor", new { authorId, bookId = bookToReturn.Id }, bookToReturn));
        }
        public IActionResult CreateBookForAuthor(Guid authorId, [FromBody] BookForCreationDto book)
        {
            if (book == null)
            {
                return(BadRequest());
            }
            // Add custom rule and add that to the model state
            if (book.Title == book.Description)
            {
                ModelState.AddModelError(nameof(BookForCreationDto), "The description should be different from the book title.");
            }
            if (!ModelState.IsValid)
            {
                // retrun 422[Un-Processable entity]
                return(new UnProcessableEntityObjectResult(ModelState));
            }
            if (!_libraryRepository.AuthorExists(authorId))
            {
                return(NotFound());
            }
            var bookEntity = _mapper.Map <Book>(book);

            _libraryRepository.AddBookForAuthor(authorId, bookEntity);
            if (!_libraryRepository.Save())
            {
                return(StatusCode(500, "Error Occurred while adding the book for the author."));
            }
            var bookToReturn = _mapper.Map <BookDto>(bookEntity);

            return(CreatedAtRoute("GetBookForAuthor", new { authorId = bookToReturn.AuthorId, id = bookToReturn.Id }, CreateLinksForBook(bookToReturn)));
        }
Esempio n. 18
0
        public IActionResult CreateBookForAuthor(Guid authorId, [FromBody] BookForCreationDto book)
        {
            if (book == null)
            {
                return(BadRequest());
            }
            if (book.Description == book.Title)
            {
                ModelState.AddModelError(nameof(BookForCreationDto), "The provided description should be different from the title.");
            }
            if (!ModelState.IsValid)
            {
                return(new UnprocessableEntityObjectResult(ModelState));
            }
            if (!_libraryRepository.AuthorExists(authorId))
            {
                return(NotFound());
            }
            var bookEntity = Mapper.Map <Book>(book);

            _libraryRepository.AddBookForAuthor(authorId, bookEntity);
            if (!_libraryRepository.Save())
            {
                throw new Exception($"Creating a book for author {authorId} failed on save.");
            }
            var bookToReturn = Mapper.Map <BookDto>(bookEntity);

            return(CreatedAtRoute("GetBookFroAuthor", new { authorId, id = bookToReturn.Id }, CreateLinksForBook(bookToReturn)));
        }
Esempio n. 19
0
        public IActionResult CreateBookForAuthor(Guid authorId,
                                                 [FromBody] BookForCreationDto book)
        {
            if (book == null)
            {
                return(BadRequest());
            }

            if (book.Description == book.Title)
            {
                //  NAME of the property to be sent in headers as Key value pair
                ModelState.AddModelError(nameof(BookForCreationDto),
                                         "The provided description should be different from the title.");
                //  VALUE of the property to be sent in headers as Key value pair
            }

            if (!ModelState.IsValid)
            {
                // return 422
                // Custom Error Handler => returns the Key Value pair Error of the specific property
                //( e.g. Title, Description ) which causes error    =>  Below is example

                /*
                 *  {
                 *      "title": [
                 *          "The title shouldn't have more than 100 characters."
                 *      ],
                 *      "description": [
                 *          "The description shouldn't have more than 500 characters."
                 *      ],
                 *      "bookForCreationDto": [
                 *          "The provided description should be different from the title."
                 *      ]
                 *  }
                 */
                return(new UnprocessableEntityObjectResult(ModelState));
            }

            if (!_libraryRepository.AuthorExists(authorId))
            {
                return(NotFound());
            }

            var bookEntity = Mapper.Map <Book>(book);

            _libraryRepository.AddBookForAuthor(authorId, bookEntity);

            if (!_libraryRepository.Save())
            {
                throw new Exception($"Creating a book for author {authorId} failed on save.");
            }

            var bookToReturn = Mapper.Map <BookDto>(bookEntity);

            return(CreatedAtRoute("GetBookForAuthor",
                                  new { authorId = authorId, id = bookToReturn.Id },
                                  //  CreateLinksForBooks => Supporting HATEOAS (Base and Wrapper Class Approach)
                                  CreateLinksForBook(bookToReturn)));
        }
Esempio n. 20
0
 public static Book Map(this BookForCreationDto book)
 {
     return(new Book
     {
         Title = book.Title,
         Description = book.Description
     });
 }
Esempio n. 21
0
        public static Book ConvertToBookEntity(this BookForCreationDto inputBook)
        {
            Book bookEntity = new Book()
            {
                Title       = inputBook.Title,
                Description = inputBook.Description
            };

            return(bookEntity);
        }
Esempio n. 22
0
        public ActionResult <BookDto> CreateBook(BookForCreationDto bookForCreationDto)
        {
            var book = _mapper.Map <Book>(bookForCreationDto);

            _bookRepository.AddBook(book);
            _bookRepository.Save();

            var bookDto = _mapper.Map <BookDto>(book);

            return(CreatedAtRoute("GetBook", new { bookId = book.Id }, bookDto));
        }
Esempio n. 23
0
        public ActionResult <BookDto> CreateBook(BookForCreationDto book)
        {
            var bookEntity = _mapper.Map <Entities.Book>(book);

            _bookRepository.AddBook(bookEntity);
            _bookRepository.Save();

            var bookToReturn = _mapper.Map <BookDto>(bookEntity);

            return(CreatedAtRoute("GetBook", new { bookId = bookToReturn.Id }, bookToReturn));
        }
Esempio n. 24
0
        public async Task <ActionResult <BookDto> > CreateBook(BookForCreationDto bookForCreation)
        {
            var book = _mapper.Map <Book>(bookForCreation);

            _booksRepository.AddBook(book);

            await _booksRepository.SaveChangesAsync();

            await _booksRepository.GetBookAsync(book.Id);

            return(CreatedAtAction(nameof(GetBook), new { id = book.Id }, _mapper.Map <BookDto>(book)));
        }
Esempio n. 25
0
        public ActionResult <BookDto> CreateBook(BookForCreationDto bookForCreationDto)
        {
            var bookModel = _mapper.Map <Book>(bookForCreationDto);

            _baseLibRepository.AddBook(bookModel);
            _baseLibRepository.SaveChanges();

            var bookReadDto = _mapper.Map <BookDto>(bookModel);

            return(CreatedAtRoute("GetBook",
                                  new { bookId = bookReadDto.Id }, bookReadDto));
        }
        public async Task <IActionResult> CreateBookAsync([FromBody] BookForCreationDto book)
        {
            var bookEntity = _mapper.Map <Book>(book);

            _bookRepository.AddBook(bookEntity);
            await _bookRepository.Save();

            return(CreatedAtRoute(
                       "GetBook",
                       new { id = bookEntity.Id },
                       bookEntity));
        }
Esempio n. 27
0
        public async Task <IActionResult> AddBook(BookForCreationDto bookForCreationDto)
        {
            var book = _mapper.Map <Book>(bookForCreationDto);

            _repo.Add(book);

            if (await _repo.SaveAll())
            {
                return(CreatedAtRoute("GetBooks", null));
            }

            return(BadRequest("Could not add the book"));
        }
Esempio n. 28
0
        public IActionResult CreateBookForAuthor(Guid authorId, [FromBody] BookForCreationDto book, [FromHeader(Name = "Accept")] string mediaType)
        {
            if (book is null)
            {
                return(BadRequest());
            }

            if (book.Description == book.Title)
            {
                ModelState.AddModelError(nameof(BookForCreationDto), "description can not be the same as title");
            }

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

            if (!_libraryRepository.AuthorExists(authorId))
            {
                return(NotFound());
            }

            var bookEntity = Mapper.Map <Book>(book);

            _libraryRepository.AddBookForAuthor(authorId, bookEntity);

            if (!_libraryRepository.Save())
            {
                throw new Exception($"book fails in save for author {authorId}");
            }

            var bookToReturn = Mapper.Map <BookDto>(bookEntity);

            if (mediaType == "application/vnd.marvin.hateoas+json")
            {
                var links = CreateLinksForBook(bookToReturn.Id);
                var linkedResourceToReturn = bookToReturn.ShapeData(null) as IDictionary <string, object>;

                linkedResourceToReturn.Add("links", links);

                return(CreatedAtRoute("GetBookForAuthor",
                                      new { authorId = authorId, id = bookToReturn.Id },
                                      linkedResourceToReturn));
            }
            else
            {
                return(CreatedAtRoute("GetBookForAuthor",
                                      new { authorId = authorId, id = bookToReturn.Id },
                                      bookToReturn));
            }
        }
Esempio n. 29
0
        public async Task AddABookTest()
        {
            BookForCreationDto newBook = new BookForCreationDto()
            {
                Title       = "Algorithms to Live by: The Computer Science of Human Decisions",
                Description = "A fascinating exploration of how insights from computer algorithms can be applied to our everyday lives, helping to solve common decision-making problems and illuminate the workings of the human mind",
                Publisher   = "Macmillan USA",
                ISBN        = "978-1627790369",
                Genres      = new List <string>()
                {
                    "Psychology",
                    "Business Decision Making Skills",
                    "Maths"
                },
                Language = "English",
                Authors  = new List <AuthorForCreationDto>()
                {
                    new AuthorForCreationDto()
                    {
                        FirstName   = "Brian",
                        LastName    = "Christian",
                        DateOfBirth = DateTimeOffset.Parse("1984-07-28T00:00:00.000Z")
                    },
                    new AuthorForCreationDto()
                    {
                        FirstName   = "Tom",
                        LastName    = "Griffiths",
                        DateOfBirth = DateTimeOffset.Parse("1987-08-02T00:00:00.000Z")
                    }
                }
            };

            var json          = JsonConvert.SerializeObject(newBook);
            var stringContent = new StringContent(json, UnicodeEncoding.UTF8, "application/json");

            _client.DefaultRequestHeaders.Authorization =
                new AuthenticationHeaderValue("Bearer", await GetJwtAsync());

            var response = await _client.PostAsync("/api/books", stringContent);

            response.EnsureSuccessStatusCode();
            var stringResponse = await response.Content.ReadAsStringAsync();

            var result = JsonConvert.DeserializeObject <BookDto>(stringResponse);

            Assert.NotNull(result);
            Assert.Equal(newBook.Title, result.Title);
            Assert.True(result.Authors.Count() == newBook.Authors.Count());
            Assert.True(result.Genres.Count() == newBook.Genres.Count());
            Assert.True(result.Language == newBook.Language);
        }
Esempio n. 30
0
        public ActionResult<BookDto> CreateBookForAuthor(Guid authorId, BookForCreationDto book)
        {
            if (!_restApiRepository.AuthorExists(authorId))
            {
                return NotFound();
            }
            var bookEntity = _mapper.Map<Book>(book);
            _restApiRepository.AddBook(authorId, bookEntity);
            _restApiRepository.Save();

            var bookToReturn = _mapper.Map<BookDto>(bookEntity);
            return CreatedAtRoute("GetBookForAuthor", new { authorId, bookId = bookToReturn.Id }, bookToReturn);

        }