chaosbot/ChaosBot/Services/LodestoneHttpProxy.cs

67 lines
2.4 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using ChaosBot.Lodestone;
using Newtonsoft.Json;
using NLog;
using NLog.Fluent;
namespace ChaosBot.Services
{
public static class LodestoneHttpProxy
{
public static T Fetch<T>(string endpoint)
{
// TODO: implement some sort of local caching
return Fetch<T>(endpoint, new Dictionary<string, string>());
}
public static T Fetch<T>(string endpoint, Dictionary<string, string> parameters)
{
// TODO: implement some sort of local caching
return LodestoneHttpConnection.Fetch<T>(endpoint, parameters).GetAwaiter().GetResult();
}
}
static class LodestoneHttpConnection
{
private static readonly ILogger _logger = Dependency.GetInstance<ILogger>();
static HttpClient client = new HttpClient();
private static bool _firstRun = true;
public static async Task<T> Fetch<T>(string endpoint, Dictionary<string, string> parameters)
{
try
{
if (_firstRun)
{
_firstRun = false;
client.BaseAddress = new Uri("https://xivapi.com/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
}
string queryString = String.Join("&",parameters.Select(param => $"{param.Key}={param.Value}").ToArray());
HttpResponseMessage response = await client.GetAsync($"{endpoint}?{queryString}");
string output = null;
if (response.IsSuccessStatusCode)
{
output = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(output);
}
throw new HttpRequestException($"HTTP Response for '{response.RequestMessage.RequestUri}' returned status code {response.StatusCode}");
}
catch (Exception ex)
{
_logger.Error(ex, $"HttpProxy.fetch<{typeof(T)}>: Exception [{ex}] thrown, <[{ex.Message}]>.");
throw;
}
}
}
}