This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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