using HomeLibrary.Api.Extensions; using HomeLibrary.Api.Repositories.Contracts; using HomeLibrary.Models.Dtos; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace HomeLibrary.Api.Controllers { [Route("api/[controller]")] [ApiController] public class BookController : ControllerBase { private readonly IBookRepository bookRepository; public BookController(IBookRepository bookRepository) { this.bookRepository = bookRepository; } [HttpGet] public async Task>> GetBooks() { try { var books = await this.bookRepository.GetBooks(); var authors = await this.bookRepository.GetAuthors(); if(books == null || authors == null) { return NotFound(); } else { var completeBookDtos = books.ConvertToDto(authors); return Ok(completeBookDtos); } } catch (Exception) { return StatusCode(StatusCodes.Status500InternalServerError, "Error retrieving data from the database."); } } [HttpGet("GetBooksByAuthorId")] public async Task>> GetBooksByAuthor(int authorId) { try { var books = await this.bookRepository.GetBooksByAuthor(authorId); if(books == null) { return NotFound(); } else { var bookDtos = books.ConvertToDto(); return Ok(bookDtos); } } catch (Exception) { return StatusCode(StatusCodes.Status500InternalServerError, "Error retrieving data from the database."); } } [HttpGet("GetBooksByAuthorName")] public async Task>> GetBooksByAuthor(string authorName) { try { var books = await this.bookRepository.GetBooksByAuthor(authorName); if (books == null) { return NotFound(); } else { var bookDtos = books.ConvertToDto(); return Ok(bookDtos); } } catch (Exception) { return StatusCode(StatusCodes.Status500InternalServerError, "Error retrieving data from the database."); } } } }