| | | 1 | | using BookstoreAPI.Models; |
| | | 2 | | using System.Text.Json; |
| | | 3 | | using BookstoreAPI.Services; |
| | | 4 | | using System.Drawing; |
| | | 5 | | |
| | | 6 | | namespace BookstoreAPI.Services |
| | | 7 | | { |
| | | 8 | | public class ExternalBookHttpClientException : Exception |
| | | 9 | | { |
| | 2 | 10 | | public ExternalBookHttpClientException(string message, Exception innerException) : base(message, innerException) |
| | 2 | 11 | | { |
| | 2 | 12 | | } |
| | | 13 | | } |
| | | 14 | | public class ExternalBookHttpClient : IExternalBookHttpClient |
| | | 15 | | { |
| | | 16 | | private readonly HttpClient _httpClient; |
| | | 17 | | |
| | | 18 | | public ExternalBookHttpClient(HttpClient httpClient) |
| | | 19 | | { |
| | | 20 | | _httpClient = httpClient; |
| | | 21 | | } |
| | | 22 | | |
| | | 23 | | public async Task<Book?> FetchBookDetailsAsync(string isbn) |
| | | 24 | | { |
| | | 25 | | try |
| | | 26 | | { |
| | | 27 | | var response = await _httpClient.GetStringAsync($"https://www.googleapis.com/books/v1/volumes?q=isbn:{is |
| | | 28 | | |
| | | 29 | | var bookData = JsonSerializer.Deserialize<JsonElement>(response); |
| | | 30 | | |
| | | 31 | | var items = bookData.GetProperty("items"); |
| | | 32 | | |
| | | 33 | | if (items.GetArrayLength() == 0) |
| | | 34 | | { |
| | | 35 | | return null; |
| | | 36 | | } |
| | | 37 | | |
| | | 38 | | var volumeInfo = items[0].GetProperty("volumeInfo"); |
| | | 39 | | |
| | | 40 | | return new Book |
| | | 41 | | { |
| | | 42 | | Title = volumeInfo.GetProperty("title").GetString(), |
| | | 43 | | Author = volumeInfo.GetProperty("authors")[0].GetString(), |
| | | 44 | | ISBN = isbn, |
| | | 45 | | Description = volumeInfo.GetProperty("description").GetString() |
| | | 46 | | }; |
| | | 47 | | } |
| | | 48 | | catch (HttpRequestException ex) |
| | | 49 | | { |
| | | 50 | | throw new ExternalBookHttpClientException("Failed to fetch book details from external API", ex); |
| | | 51 | | } |
| | | 52 | | } |
| | | 53 | | } |
| | | 54 | | } |
| | | 55 | | |