using System; using System.Net.Http; using System.Net.Http.Headers; using System.Text.Json; using System.Threading.Tasks; namespace winui_learning_2.Services; public class NodplayApiClient { private static readonly JsonSerializerOptions JsonOptions = new() { PropertyNameCaseInsensitive = true }; private readonly HttpClient _httpClient = new() { BaseAddress = new Uri(ApiConstants.BaseUrl) }; public async Task GetAsync(string path) { using var request = CreateRequest(HttpMethod.Get, path); using var response = await _httpClient.SendAsync(request); if (!response.IsSuccessStatusCode) { var body = await response.Content.ReadAsStringAsync(); throw new NodplayApiException((int)response.StatusCode, body); } var json = await response.Content.ReadAsStringAsync(); if (string.IsNullOrWhiteSpace(json)) { return default; } return JsonSerializer.Deserialize(json, JsonOptions); } private static HttpRequestMessage CreateRequest(HttpMethod method, string path) { var request = new HttpRequestMessage(method, path); if (!string.IsNullOrEmpty(AuthSession.Token)) { request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", AuthSession.Token); } return request; } } public class NodplayApiException : Exception { public int StatusCode { get; } public NodplayApiException(int statusCode, string? body) : base(string.IsNullOrWhiteSpace(body) ? $"API request failed ({statusCode})." : body) { StatusCode = statusCode; } }