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 Logger _logger = Program._logger;
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;
}
}
}
}