using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.WebUtilities; using Newtonsoft.Json; namespace Website.Data { public abstract class ApiClient { private readonly HttpClient _client; protected ApiClient(HttpClient client) { _client = client; } private IDictionary ParseQueryParameters(object query) { var type = query.GetType(); var props = type.GetProperties(); return props.ToDictionary(info => info.Name, info => info.GetValue(query, null).ToString()); } private async Task Send(HttpMethod method, string url, object query, HttpContent content = null) { if (query != null) url = QueryHelpers.AddQueryString(url, ParseQueryParameters(query)); using var httpRequest = new HttpRequestMessage(method, url) { Content = content }; var response = await _client.SendAsync(httpRequest); if (!response.IsSuccessStatusCode) throw new ApiCallException(response); var json = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject(json); } protected async Task Post(string url, object value, object query = null) { var json = JsonConvert.SerializeObject(value); using var requestBody = new StringContent(json, Encoding.UTF8, "application/json"); return await Send(HttpMethod.Post, url, query, requestBody); } protected async Task Get(string url, object query = null) { return await Send(HttpMethod.Get, url, query); } } }