Přidání nového projektu - pokus o explorer
This commit is contained in:
1 parent
b0b0b3ee34
commit
d06a9f332b
48 files changed
+1429
No files matched your search
@@ -0,0 +1,66 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user