using System; using System.Net.Http; using System.Text; using System.Text.Json; using System.Threading.Tasks; using EstusShots.Shared.Interfaces; using EstusShots.Shared.Models; namespace EstusShots.Client { public partial class EstusShotsClient { private readonly JsonSerializerOptions _serializerOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; private HttpClient HttpClient { get; } public string ApiUrl { get; } /// /// Creates a new instance of /// /// Base URL of the Estus Shots API host public EstusShotsClient(string apiUrl) { ApiUrl = apiUrl; HttpClient = new HttpClient {Timeout = TimeSpan.FromSeconds(10)}; CreateApiRoutes(); } /// /// Generic method to post a request to the API /// /// URL to the desired action /// The API parameter object instance /// API response class that implements /// API parameter class that implements /// internal async Task> PostToApi(string url, TParam parameter) where TParam : IApiParameter, new() where TResult : class, IApiResponse, new() { try { var serialized = JsonSerializer.Serialize(parameter); var content = new StringContent(serialized, Encoding.UTF8, "application/json"); var response = await HttpClient.PostAsync(url, content); response.EnsureSuccessStatusCode(); var json = await response.Content.ReadAsStringAsync(); if (json.IsNullOrWhiteSpace() || json == "{}") return new ApiResponse(new OperationResult(false, "Invalid response", "The server returned no or empty data")); var result = JsonSerializer.Deserialize>(json, _serializerOptions); return result; } catch (Exception e) { return new ApiResponse(new OperationResult(e)); } } } }