new endpoint for the market chart data

pull/1278/head
Gustavo Santos Ferreira 6 years ago
parent 47886ae50d
commit bc48b8ea23
  1. 51
      apps/block_scout_web/lib/block_scout_web/controllers/chain/market_history_chart_controller.ex
  2. 2
      apps/block_scout_web/lib/block_scout_web/router.ex
  3. 24
      apps/block_scout_web/test/block_scout_web/controllers/chain/market_history_chart_controller_test.exs

@ -0,0 +1,51 @@
defmodule BlockScoutWeb.Chain.MarketHistoryChartController do
use BlockScoutWeb, :controller
alias Explorer.{Chain, Market}
alias Explorer.ExchangeRates.Token
def show(conn, _params) do
with true <- ajax?(conn) do
exchange_rate = Market.get_exchange_rate(Explorer.coin()) || Token.null()
market_history_data =
30
|> Market.fetch_recent_history()
|> case do
[today | the_rest] -> [%{today | closing_price: exchange_rate.usd_value} | the_rest]
data -> data
end
|> encode_market_history_data()
json(conn, %{
history_data: market_history_data,
supply_data: available_supply(Chain.supply_for_days(30), exchange_rate)
})
else
_ -> unprocessable_entity(conn)
end
end
defp available_supply(:ok, exchange_rate) do
to_string(exchange_rate.available_supply || 0)
end
defp available_supply({:ok, supply_for_days}, _exchange_rate) do
supply_for_days
|> Jason.encode()
|> case do
{:ok, data} -> data
_ -> []
end
end
defp encode_market_history_data(market_history_data) do
market_history_data
|> Enum.map(fn day -> Map.take(day, [:closing_price, :date]) end)
|> Jason.encode()
|> case do
{:ok, data} -> data
_ -> []
end
end
end

@ -66,6 +66,8 @@ defmodule BlockScoutWeb.Router do
resources("/", ChainController, only: [:show], singleton: true, as: :chain)
resources("/market_history_chart", Chain.MarketHistoryChartController, only: [:show], singleton: true)
resources "/blocks", BlockController, only: [:index, :show], param: "hash_or_number" do
resources("/transactions", BlockTransactionController, only: [:index], as: :transaction)
end

@ -0,0 +1,24 @@
defmodule BlockScoutWeb.Chain.MarketHistoryChartControllerTest do
use BlockScoutWeb.ConnCase
describe "GET show/2" do
test "returns error when not an ajax request" do
path = market_history_chart_path(BlockScoutWeb.Endpoint, :show)
conn = get(build_conn(), path)
assert conn.status == 422
end
test "returns ok when request is ajax" do
path = market_history_chart_path(BlockScoutWeb.Endpoint, :show)
conn =
build_conn()
|> put_req_header("x-requested-with", "xmlhttprequest")
|> get(path)
assert json_response(conn, 200)
end
end
end
Loading…
Cancel
Save