From 34dd660c1f1a31e238e314508858a1034310ba27 Mon Sep 17 00:00:00 2001 From: Gustavo Santos Ferreira Date: Fri, 28 Dec 2018 14:27:48 -0200 Subject: [PATCH] deal with coin market cap's pagination situation --- .../lib/explorer/exchange_rates/source.ex | 28 +++++++++++++++++++ .../exchange_rates/source/coin_market_cap.ex | 8 +++++- 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/apps/explorer/lib/explorer/exchange_rates/source.ex b/apps/explorer/lib/explorer/exchange_rates/source.ex index 7401d27a0d..584f7bf147 100644 --- a/apps/explorer/lib/explorer/exchange_rates/source.ex +++ b/apps/explorer/lib/explorer/exchange_rates/source.ex @@ -3,6 +3,7 @@ defmodule Explorer.ExchangeRates.Source do Behaviour for fetching exchange rates from external sources. """ + alias Explorer.ExchangeRates.Source.CoinMarketCap alias Explorer.ExchangeRates.Token alias HTTPoison.{Error, Response} @@ -11,6 +12,31 @@ defmodule Explorer.ExchangeRates.Source do """ @spec fetch_exchange_rates(module) :: {:ok, [Token.t()]} | {:error, any} def fetch_exchange_rates(source \\ exchange_rates_source()) do + if(source == CoinMarketCap) do + fetch_exchange_rates_from_paginable_source(source) + else + fetch_exchange_rates_request(source) + end + end + + defp fetch_exchange_rates_from_paginable_source(source, page \\ 1) do + case HTTPoison.get(source.source_url(page), headers()) do + {:ok, %Response{body: body, status_code: 200}} -> + cond do + body =~ Explorer.coin() -> {:ok, source.format_data(body)} + page == source.max_page_number -> {:error, "exchange rates not found for this network"} + true -> fetch_exchange_rates_from_paginable_source(source, page + 1) + end + + {:ok, %Response{body: body, status_code: status_code}} when status_code in 400..499 -> + {:error, decode_json(body)["error"]} + + {:error, %Error{reason: reason}} -> + {:error, reason} + end + end + + defp fetch_exchange_rates_request(source) do case HTTPoison.get(source.source_url(), headers()) do {:ok, %Response{body: body, status_code: 200}} -> {:ok, source.format_data(body)} @@ -43,6 +69,8 @@ defmodule Explorer.ExchangeRates.Source do def to_decimal(nil), do: nil + def to_decimal(%Decimal{} = value), do: value + def to_decimal(value) when is_float(value) do Decimal.from_float(value) end diff --git a/apps/explorer/lib/explorer/exchange_rates/source/coin_market_cap.ex b/apps/explorer/lib/explorer/exchange_rates/source/coin_market_cap.ex index 568a9f36d1..4030eed06f 100644 --- a/apps/explorer/lib/explorer/exchange_rates/source/coin_market_cap.ex +++ b/apps/explorer/lib/explorer/exchange_rates/source/coin_market_cap.ex @@ -31,9 +31,15 @@ defmodule Explorer.ExchangeRates.Source.CoinMarketCap do @impl Source def source_url do - "#{base_url()}/v1/ticker/?limit=0" + source_url(1) end + def source_url(page) do + "#{base_url()}/v1/ticker/?start=#{page - 1}00" + end + + def max_page_number, do: 10 + defp base_url do config(:base_url) || "https://api.coinmarketcap.com" end