constellation-api/CH.CryptoStats.CoinGecko/CoinGeckoService.cs

39 lines
1.7 KiB
C#

using CH.CryptoStats.Abstractions;
using Microsoft.Extensions.Configuration;
using System.Net.Http.Json;
using System.Text.Json;
using CH.Energy.Abstractions.Enum;
namespace CH.CryptoStats.CoinGecko;
public class CoinGeckoService(IConfiguration configuration, HttpClient httpClient) : ICryptoStats
{
public async Task<Abstractions.CryptoStats> GetCryptoStatsAsync(string cryptoName, string currency, CancellationToken cancellationToken)
{
var apiKey = configuration.GetValue<string>("CoinGecko:ApiKey");
var apiUrl = configuration.GetValue<string>("CoinGecko:ApiUrl");
var response = await httpClient.GetAsync($"{apiUrl}?ids={cryptoName}&vs_currency={currency}&x_cg_demo_api_key={apiKey}",cancellationToken);
var jsonResponse = await response.Content.ReadFromJsonAsync<List<CoinGeckoEntity>>(cancellationToken);
return ParseCryptoStats(jsonResponse.FirstOrDefault(), currency, cancellationToken).Result;
}
private Task<Abstractions.CryptoStats> ParseCryptoStats(CoinGeckoEntity coinGeckoEntity, string currency, CancellationToken cancellationToken)
{
var cryptoStats = new Abstractions.CryptoStats
{
Name = coinGeckoEntity.Name,
Symbol = coinGeckoEntity.Symbol,
MaxSupply = coinGeckoEntity.MaxSupply,
CirculatingSupply = coinGeckoEntity.CirculatingSupply,
TotalSupply = coinGeckoEntity.TotalSupply,
Currency = (Currency)System.Enum.Parse(typeof(Currency), currency.ToUpper()),
UpdatedAt = coinGeckoEntity.LastUpdated,
Price = coinGeckoEntity.Price,
MarketCap = coinGeckoEntity.MarketCap,
FullyDilutedMarketCap = coinGeckoEntity.FullyDilutedValuation
};
return Task.FromResult(cryptoStats);
}
}