website/Website/Data/ApiClient.cs

48 lines
1.5 KiB
C#

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<string, string> 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<T> Send<T>(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<T>(json);
}
protected async Task<T> Post<T>(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<T>(HttpMethod.Post, url, query, requestBody);
}
protected async Task<T> Get<T>(string url, object query = null) {
return await Send<T>(HttpMethod.Get, url, query);
}
}
}