Refactor in initialization NewCoinGeckoDownloader

This commit is contained in:
romanornr 2023-12-19 00:12:36 +01:00 committed by Martin
parent f6edc06630
commit e7ee4a95d8

View File

@ -17,6 +17,11 @@ import (
"github.com/trezor/blockbook/db"
)
const (
DefaultHTTPTimeout = 15 * time.Second
DefaultThrottleDelayMs = 100 // 100 ms delay between requests
)
// Coingecko is a structure that implements RatesDownloaderInterface
type Coingecko struct {
url string
@ -55,18 +60,13 @@ type marketChartPrices struct {
// NewCoinGeckoDownloader creates a coingecko structure that implements the RatesDownloaderInterface
func NewCoinGeckoDownloader(db *db.RocksDB, url string, coin string, platformIdentifier string, platformVsCurrency string, allowedVsCurrencies string, timeFormat string, metrics *common.Metrics, throttleDown bool) RatesDownloaderInterface {
var throttlingDelayMs int
throttlingDelayMs := 0 // No delay by default
if throttleDown {
throttlingDelayMs = 100
}
httpTimeout := 15 * time.Second
allowedVsCurrenciesMap := make(map[string]struct{})
if len(allowedVsCurrencies) > 0 {
for _, c := range strings.Split(strings.ToLower(allowedVsCurrencies), ",") {
allowedVsCurrenciesMap[c] = struct{}{}
}
throttlingDelayMs = DefaultThrottleDelayMs
}
allowedVsCurrenciesMap := getAllowedVsCurrenciesMap(allowedVsCurrencies)
apiKey := os.Getenv("COINGECKO_API_KEY")
// use default address if not overridden, with respect to existence of apiKey
@ -86,10 +86,10 @@ func NewCoinGeckoDownloader(db *db.RocksDB, url string, coin string, platformIde
platformIdentifier: platformIdentifier,
platformVsCurrency: platformVsCurrency,
allowedVsCurrencies: allowedVsCurrenciesMap,
httpTimeout: httpTimeout,
httpTimeout: DefaultHTTPTimeout,
timeFormat: timeFormat,
httpClient: &http.Client{
Timeout: httpTimeout,
Timeout: DefaultHTTPTimeout,
},
db: db,
throttlingDelay: time.Duration(throttlingDelayMs) * time.Millisecond,
@ -97,6 +97,17 @@ func NewCoinGeckoDownloader(db *db.RocksDB, url string, coin string, platformIde
}
}
// getAllowedVsCurrenciesMap returns a map of allowed vs currencies
func getAllowedVsCurrenciesMap(currenciesString string) map[string]struct{} {
allowedVsCurrenciesMap := make(map[string]struct{})
if len(currenciesString) > 0 {
for _, c := range strings.Split(strings.ToLower(currenciesString), ",") {
allowedVsCurrenciesMap[c] = struct{}{}
}
}
return allowedVsCurrenciesMap
}
// doReq HTTP client
func doReq(req *http.Request, client *http.Client) ([]byte, error) {
resp, err := client.Do(req)