using System; using System.Net.Http; using System.Text; using System.Text.Json; using System.Threading.Tasks; using EstusShots.Client.Routes; using EstusShots.Shared.Dto; using EstusShots.Shared.Interfaces; using EstusShots.Shared.Models; namespace EstusShots.Client { public class EstusShotsClient { private readonly JsonSerializerOptions _serializerOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; private HttpClient HttpClient { get; } public string ApiUrl { get; } // API Routes public Seasons Seasons { get; } public Episodes Episodes { get; } public Players Players { get; } public Drinks Drinks { get; } public Enemies Enemies { 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)}; Seasons = new Seasons(this); Episodes = new Episodes(this); Players = new Players(this); Drinks = new Drinks(this); Enemies = new Enemies(this); } /// /// 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)); } } } }