deal with coin market cap's pagination situation

pull/1278/head
Gustavo Santos Ferreira 6 years ago
parent ae7bd4aefc
commit 34dd660c1f
  1. 28
      apps/explorer/lib/explorer/exchange_rates/source.ex
  2. 8
      apps/explorer/lib/explorer/exchange_rates/source/coin_market_cap.ex

@ -3,6 +3,7 @@ defmodule Explorer.ExchangeRates.Source do
Behaviour for fetching exchange rates from external sources. Behaviour for fetching exchange rates from external sources.
""" """
alias Explorer.ExchangeRates.Source.CoinMarketCap
alias Explorer.ExchangeRates.Token alias Explorer.ExchangeRates.Token
alias HTTPoison.{Error, Response} alias HTTPoison.{Error, Response}
@ -11,6 +12,31 @@ defmodule Explorer.ExchangeRates.Source do
""" """
@spec fetch_exchange_rates(module) :: {:ok, [Token.t()]} | {:error, any} @spec fetch_exchange_rates(module) :: {:ok, [Token.t()]} | {:error, any}
def fetch_exchange_rates(source \\ exchange_rates_source()) do 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 case HTTPoison.get(source.source_url(), headers()) do
{:ok, %Response{body: body, status_code: 200}} -> {:ok, %Response{body: body, status_code: 200}} ->
{:ok, source.format_data(body)} {:ok, source.format_data(body)}
@ -43,6 +69,8 @@ defmodule Explorer.ExchangeRates.Source do
def to_decimal(nil), do: nil def to_decimal(nil), do: nil
def to_decimal(%Decimal{} = value), do: value
def to_decimal(value) when is_float(value) do def to_decimal(value) when is_float(value) do
Decimal.from_float(value) Decimal.from_float(value)
end end

@ -31,9 +31,15 @@ defmodule Explorer.ExchangeRates.Source.CoinMarketCap do
@impl Source @impl Source
def source_url do def source_url do
"#{base_url()}/v1/ticker/?limit=0" source_url(1)
end 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 defp base_url do
config(:base_url) || "https://api.coinmarketcap.com" config(:base_url) || "https://api.coinmarketcap.com"
end end

Loading…
Cancel
Save