67 lines
1.7 KiB
C#
67 lines
1.7 KiB
C#
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<T?> GetAsync<T>(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<T>(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;
|
|
}
|
|
}
|