Skip to content

Instantly share code, notes, and snippets.

@dcomartin
Created March 16, 2023 19:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dcomartin/b335ecf2843132b04cef02fe8336b2ea to your computer and use it in GitHub Desktop.
Save dcomartin/b335ecf2843132b04cef02fe8336b2ea to your computer and use it in GitHub Desktop.
public class ExchangeRateClient : IExchangeRateClient
{
private readonly HttpClient _httpClient;
private readonly IMemoryCache _memoryCache;
public ExchangeRateClient(HttpClient httpClient, IMemoryCache memoryCache)
{
_httpClient = httpClient;
_memoryCache = memoryCache;
}
private string Key(DateOnly date)
{
return $"Rate:{date.ToString("yyyy-MM-dd")}";
}
public async Task<decimal> Rate(DateOnly date, Currency baseCurrency, Currency toCurrency)
{
return await _memoryCache.GetOrCreateAsync(Key(date), async _ =>
{
var result = await _httpClient.GetFromJsonAsync<JsonResponse>(
$"https://data.fixer.io/api/{date.ToString("yyyy-MM-dd")}?base={baseCurrency}&symbols={toCurrency}");
if (result == null)
{
throw new InvalidOperationException("Not a valid JSON response.");
}
return result.Rates.Single(x => x.Key == toCurrency.ToString()).Value;
});
}
private class JsonResponse
{
public Dictionary<string, decimal> Rates { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment