示例#1
0
        public async Task <ActionResult <BookDTO> > CreateBook([FromBody] SaveBookDTO saveBook)
        {
            try
            {
                var validator        = new SaveBookResourceValidator();
                var validationResult = await validator.ValidateAsync(saveBook);

                if (!validationResult.IsValid)
                {
                    return(BadRequest(validationResult.Errors));
                }

                var bookCreation = _mapper.Map <SaveBookDTO, Book>(saveBook);
                var newBook      = await _bookService.Create(bookCreation);

                var book = await _bookService.GetBookById(newBook.Id);

                var bookRes = _mapper.Map <Book, BookDTO>(book);

                return(BuildObjectResult(HttpStatusCode.OK, true, value: bookRes));
            }
            catch (Exception ex)
            {
                return(BuildObjectResult(HttpStatusCode.BadRequest, false, ex.Message));
            }
        }
示例#2
0
        public async Task <ActionResult <BookDTO> > UpdateBook([FromRoute] int id, [FromBody] SaveBookDTO saveBook)
        {
            try
            {
                var validator        = new SaveBookResourceValidator();
                var validationResult = await validator.ValidateAsync(saveBook);

                var requestIsInvalid = id == 0 || !validationResult.IsValid;

                if (requestIsInvalid)
                {
                    return(BadRequest(validationResult.Errors));
                }

                var bookToBeUpdate = await _bookService.GetBookById(id);

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

                var book = _mapper.Map <SaveBookDTO, Book>(saveBook);

                await _bookService.Update(bookToBeUpdate, book);

                var updatedBook = await _bookService.GetBookById(id);

                var updatedBookResource = _mapper.Map <Book, BookDTO>(updatedBook);


                return(BuildObjectResult(HttpStatusCode.OK, true, value: updatedBookResource));
            }
            catch (Exception e)
            {
                return(BuildObjectResult(HttpStatusCode.BadRequest, false, e.Message));
            }
        }