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