|
1 | 1 | using System.Text.Json;
|
2 | 2 | using Waffle.ExternalAPI.Interfaces;
|
3 | 3 | using Waffle.ExternalAPI.Models;
|
| 4 | +using Waffle.Models; |
4 | 5 |
|
5 |
| -namespace Waffle.ExternalAPI.Services |
| 6 | +namespace Waffle.ExternalAPI.Services; |
| 7 | + |
| 8 | +public class WordPressService : IWordPressService |
6 | 9 | {
|
7 |
| - public class WordPressService : IWordPressService |
| 10 | + private readonly HttpClient _httpClient; |
| 11 | + private readonly ILogger<WordPressService> _logger; |
| 12 | + |
| 13 | + public WordPressService(HttpClient httpClient, ILogger<WordPressService> logger) |
8 | 14 | {
|
9 |
| - private readonly HttpClient _httpClient; |
10 |
| - public WordPressService(HttpClient httpClient) |
11 |
| - { |
12 |
| - _httpClient = httpClient; |
13 |
| - } |
14 |
| - public async Task<WordPressPost?> GetPostAsync(string domain, int id) |
| 15 | + _httpClient = httpClient; |
| 16 | + _logger = logger; |
| 17 | + } |
| 18 | + |
| 19 | + public async Task<WordPressPost?> GetPostAsync(string domain, string? id) |
| 20 | + { |
| 21 | + if (string.IsNullOrEmpty(id)) return default; |
| 22 | + try |
15 | 23 | {
|
16 |
| - try |
| 24 | + var url = $"{domain}/wp-json/wp/v2/posts/{id}"; |
| 25 | + if (domain.EndsWith("/")) |
17 | 26 | {
|
18 |
| - var url = $"https://{domain}/wp-json/wp/v2/posts/{id}"; |
19 |
| - var response = await _httpClient.GetStreamAsync(url); |
20 |
| - return await JsonSerializer.DeserializeAsync<WordPressPost>(response); |
| 27 | + url = $"{domain}wp-json/wp/v2/posts/{id}"; |
21 | 28 | }
|
22 |
| - catch (Exception) |
| 29 | + var response = await _httpClient.GetStreamAsync(url); |
| 30 | + return await JsonSerializer.DeserializeAsync<WordPressPost>(response); |
| 31 | + } |
| 32 | + catch (Exception ex) |
| 33 | + { |
| 34 | + _logger.LogError("Exception {Message}", ex.Message); |
| 35 | + return default; |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + public async Task<IEnumerable<WordPressPost>?> ListPostAsync(string domain, IFilterOptions filterOptions) |
| 40 | + { |
| 41 | + try |
| 42 | + { |
| 43 | + var url = $"{domain}/wp-json/wp/v2/posts?page={filterOptions.Current}"; |
| 44 | + if (domain.EndsWith("/")) |
23 | 45 | {
|
24 |
| - return default; |
| 46 | + url = $"{domain}wp-json/wp/v2/posts?page={filterOptions.Current}"; |
25 | 47 | }
|
| 48 | + var response = await _httpClient.GetStreamAsync(url); |
| 49 | + return await JsonSerializer.DeserializeAsync<List<WordPressPost>>(response); |
| 50 | + } |
| 51 | + catch (Exception ex) |
| 52 | + { |
| 53 | + _logger.LogError("Exception {Message}", ex.Message); |
| 54 | + return default; |
26 | 55 | }
|
27 | 56 | }
|
28 | 57 | }
|
0 commit comments