Esempio n. 1
0
        public async Task <ActionResult <GetBookDetailsResponse> > AddABook([FromBody] BookCreateRequest bookToAdd)
        {
            // 1. Validate the incoming entity
            if (!ModelState.IsValid)
            {
                //  -- if it fails, send back a 400 with our without details.

                return(BadRequest(ModelState));
            }
            else
            {
                // 2. Change the domain
                //   - add the book to the database. (BookCreateRequest -> Book)
                var book = _mapper.Map <Book>(bookToAdd);
                _context.Books.Add(book);
                await _context.SaveChangesAsync();

                var response = _mapper.Map <GetBookDetailsResponse>(book);
                // 3. Return
                //    201 Created
                //    Location Header (what is the name of the new book (name being the URI))
                //    Give them a copy of the thing.

                return(CreatedAtRoute("books#getbookbyid", new { bookId = response.Id }, response));
            }
        }
Esempio n. 2
0
        public async Task <ActionResult> AddABook([FromBody] BookCreateRequest bookToAdd)
        {
            Thread.Sleep(4000);
            // "Post to a Collection" (books is the collection)
            // - "I'd like to add this representation as a new resource in your collection please"
            // 1. Validate the incoming representation. Does it look good? follow the rules? etc.
            //   - if NOT - send a 400 error. *maybe* tell them what they did wrong.
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            else
            {
                // 2. Add it to the domain.
                //   - turn our bookToAdd -> Book
                var book = _mapper.Map <Book>(bookToAdd);
                //   - Add it to the _context.Books
                _context.Books.Add(book);
                //   - tell it to save the changes.
                await _context.SaveChangesAsync();

                var response = _mapper.Map <GetBookDetailsResponse>(book);
                // 3. Return:
                //    201 Created status code.
                //    Location: http://localhost:1337/books/5 (birth announcement!)
                //    Attach to the response a copy of whatever they would get if they followed the URL at the location header.
                return(CreatedAtRoute("books#getabook", new { bookId = response.Id }, response));
            }
        }
Esempio n. 3
0
        //     public async Task<Dictionary<int, Book>> GetBooksByIdAsync(IEnumerable<int> bookIds, CancellationToken token)
        //     {
        //return await _libraryContext.Books.Where(i => bookIds.Contains(i.BookId)).ToDictionaryAsync(x => x.BookId);
        //     }

        //      public async Task<ILookup<int, BookResponse>> GetBooksByAuthorIdAsync(int authorId)
        //      {
        //          var books = await _libraryContext.Books.Where(o => o.AuthorAuthorId == authorId).ToListAsync();
        //          return _mapper.Map<IReadOnlyList<BookResponse>>(books).ToLookup(i => i.AuthorId);
        //}

        //      public async Task<ILookup<int, BookResponse>> GetBooksByAuthorIdsAsync(IEnumerable<int> authorIds)
        //      {
        //          var books = await _libraryContext.Books.Where(i => authorIds.Contains(i.AuthorAuthorId)).ToListAsync();
        //          return _mapper.Map<IReadOnlyList<BookResponse>>(books).ToLookup(i => i.AuthorId);
        //      }

        //public async Task<ILookup<int, BookResponse>> GetBooksInCoAuthoringByAuthorIdsAsync(IEnumerable<int> authorIds)
        //{
        //    var coAuthors = await _libraryContext.CoAuthorBooks.Where(x => authorIds.Contains(x.AuthorId)).ToArrayAsync();
        //    int[] bookIds = new int[coAuthors.Length];
        //    for (int i = 0; i < coAuthors.Length; i++)
        //    {
        //        bookIds[i] = coAuthors[i].BookId;
        //    }
        //    var books = await _libraryContext.Books.Where(x => bookIds.Contains(x.BookId)).ToListAsync();
        //    return _mapper.Map<IReadOnlyList<BookResponse>>(books).ToLookup(i => i.AuthorId);
        //}

        public async Task <BookResponse> CreateBookAsync(BookCreateRequest book)
        {
            var addedBook = await _libraryContext.Books.AddAsync(_mapper.Map <Book>(book));

            await _libraryContext.SaveChangesAsync();

            return(_mapper.Map <BookResponse>(addedBook.Entity));
        }
Esempio n. 4
0
        public async Task <IActionResult> CreateBookAsync(BookCreateRequest createRequest)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState.GetErrorMessages()));
            }

            var  headers  = Request.Headers;
            var  Username = string.Empty;
            byte Admin    = 0;


            if (headers.ContainsKey("Username"))
            {
                if (headers.TryGetValue("Username", out var traceValue))
                {
                    Username = traceValue;
                }
            }

            if (headers.ContainsKey("Admin"))
            {
                if (headers.TryGetValue("Admin", out var traceValue2))
                {
                    Admin = Convert.ToByte(traceValue2);
                }
            }

            if (Username != "user")
            {
                return(Ok(new { ErrorMessage = "You are not authenticated", StatusCodes = StatusCodes.Status401Unauthorized }));
            }

            if (Admin != 1)
            {
                return(Ok(new { ErrorMessage = "You are not authorized to register a book", StatusCodes = StatusCodes.Status401Unauthorized }));
            }

            var bookInfo = new BookCreateRequestModified
            {
                Title               = createRequest.Title,
                ISBN                = createRequest.ISBN,
                Cover_Price         = createRequest.Cover_Price,
                Published_Year      = createRequest.Published_Year,
                Availability_Status = true
            };
            var book   = _mapper.Map <BookCreateRequestModified, Book>(bookInfo);
            var result = await _bookservice.AddbookAsync(book);


            return(Ok(result));
        }
        public async Task <ActionResult> CreateBook([FromBody] BookCreateRequest bookCreateRequest)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var book = _mapper.Map <Book>(bookCreateRequest);

            _context.Books.Add(book);
            await _context.SaveChangesAsync();

            var response = _mapper.Map <GetBookDetailsResponse>(book);

            return(CreatedAtRoute("books#getbook", new { bookId = response.Id }, response));
        }
Esempio n. 6
0
    public async Task <ActionResult <BookResponse> > Post([FromBody] BookCreateRequest request)
    {
        if (!ModelState.IsValid)
        {
            return(BadRequest(ModelState));
        }

        var model = _mapper.Map <Book>(request);
        await _db.CreateAsync(model);

        _logger.LogInformation("Книга успешно создана");

        var result = _mapper.Map <BookResponse>(model);

        return(Ok(result));
    }
Esempio n. 7
0
        public async Task <int> Create(BookCreateRequest request)
        {
            var book = new DATA.Entities.Book()
            {
                Title     = request.Title,
                Author    = request.Author,
                Language  = request.Language,
                Publisher = new List <DATA.Entities.Publisher>()
                {
                    new DATA.Entities.Publisher()
                    {
                        Name = request.PublisherName
                    }
                }
            };

            _context.Books.Add(book);
            return(await _context.SaveChangesAsync());
        }
        public IActionResult CreateBookForAuthor(Guid authorId,
                                                 [FromBody] BookCreateRequest book)
        {
            if (book == null)
            {
                return(BadRequest());
            }

            if (book.Description == book.Title)
            {
                ModelState.AddModelError(nameof(BookCreateRequest),
                                         "The provided description should be different from the title.");
            }

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

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

            var bookEntity = book.ConvertToBook();

            _libraryRepository.AddBookForAuthor(authorId, bookEntity);

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

            var bookToReturn = new BookResponse(bookEntity);

            return(CreatedAtRoute("GetBookForAuthor",
                                  new { authorId = authorId, id = bookToReturn.Id },
                                  bookToReturn));
        }