43 lines
1.9 KiB
C#
43 lines
1.9 KiB
C#
using CH.CryptoStats.Abstractions;
|
|
using Microsoft.Extensions.Configuration;
|
|
using System.Net.Http.Json;
|
|
using System.Text.Json;
|
|
using CH.Enum;
|
|
|
|
namespace CH.CryptoStats.CoinMarketCap;
|
|
|
|
public class CoinMarketCapService(HttpClient httpClient, IConfiguration configuration) : ICryptoStats
|
|
{
|
|
public async Task<Abstractions.CryptoStats> GetCryptoStatsAsync(string cryptoName, string currency, CancellationToken cancellationToken)
|
|
{
|
|
var apiKey = configuration.GetValue<string>("CoinMarketCap:ApiKey");
|
|
var apiUrl = configuration.GetValue<string>("CoinMarketCap:ApiUrl");
|
|
var response = await httpClient.GetAsync($"{apiUrl}slug={cryptoName}&convert={currency}&CMC_PRO_API_KEY={apiKey}",cancellationToken);
|
|
var jsonResponse = await response.Content.ReadFromJsonAsync<ApiResponse>(cancellationToken);
|
|
return ParseCryptoStats(jsonResponse.Data["1"], currency, cancellationToken).Result;
|
|
|
|
}
|
|
|
|
private Task<Abstractions.CryptoStats> ParseCryptoStats(CoinMarketCapEntity coinMarketCapEntity, string currency, CancellationToken cancellationToken)
|
|
{
|
|
var quoteData = coinMarketCapEntity.Quote.CAD ?? coinMarketCapEntity.Quote.USD;
|
|
var cryptoStats = new Abstractions.CryptoStats
|
|
{
|
|
Name = coinMarketCapEntity.Name,
|
|
Symbol = coinMarketCapEntity.Symbol,
|
|
MaxSupply = coinMarketCapEntity.MaxSupply,
|
|
CirculatingSupply = coinMarketCapEntity.CirculatingSupply,
|
|
TotalSupply = coinMarketCapEntity.TotalSupply,
|
|
Currency = (Currency)System.Enum.Parse(typeof(Currency), currency.ToUpper()),
|
|
UpdatedAt = DateTime.Parse(coinMarketCapEntity.LastUpdated),
|
|
Price = quoteData.Price,
|
|
Volume24H = quoteData.Volume24H,
|
|
VolumeChange24H = quoteData.VolumeChange24H,
|
|
MarketCap = quoteData.MarketCap,
|
|
MarketCapDominance = quoteData.MarketCapDominance,
|
|
FullyDilutedMarketCap = quoteData.FullyDilutedMarketCap
|
|
};
|
|
return Task.FromResult(cryptoStats);
|
|
}
|
|
}
|