feat: Xname app proxy (#11010)
* Xname app proxy * fix specs * Process reviewer commentsvb-airtable-proxy
parent
6dbdb26b35
commit
eb94a4230f
@ -0,0 +1,24 @@ |
||||
defmodule BlockScoutWeb.API.V2.Proxy.XnameController do |
||||
use BlockScoutWeb, :controller |
||||
|
||||
alias BlockScoutWeb.API.V2.AddressController |
||||
|
||||
alias Explorer.ThirdPartyIntegrations.Xname |
||||
|
||||
action_fallback(BlockScoutWeb.API.V2.FallbackController) |
||||
|
||||
@doc """ |
||||
Function to handle GET requests to `/api/v2/proxy/xname/address/:address_hash_param` endpoint. |
||||
""" |
||||
@spec address(Plug.Conn.t(), map()) :: Plug.Conn.t() | {atom(), any()} |
||||
def address(conn, %{"address_hash_param" => address_hash_string} = params) do |
||||
with {:ok, _address_hash, _address} <- AddressController.validate_address(address_hash_string, params), |
||||
url = Xname.address_url(address_hash_string), |
||||
{response, status} <- Xname.api_request(url, conn), |
||||
{:is_empty_response, false} <- {:is_empty_response, is_nil(response)} do |
||||
conn |
||||
|> put_status(status) |
||||
|> json(response) |
||||
end |
||||
end |
||||
end |
@ -0,0 +1,50 @@ |
||||
defmodule Explorer.ThirdPartyIntegrations.Xname do |
||||
@moduledoc """ |
||||
Module for proxying xname https://xname.app/ API endpoints |
||||
""" |
||||
|
||||
require Logger |
||||
|
||||
alias Explorer.Helper |
||||
alias Explorer.Utility.Microservice |
||||
|
||||
@recv_timeout 60_000 |
||||
|
||||
@doc """ |
||||
Proxy request to XName API endpoints |
||||
""" |
||||
@spec api_request(String.t(), Plug.Conn.t(), atom()) :: {any(), integer()} |
||||
def api_request(url, conn, method \\ :get) |
||||
|
||||
def api_request(url, _conn, :get) do |
||||
headers = [{"x-api-key", api_key()}] |
||||
|
||||
case HTTPoison.get(url, headers, recv_timeout: @recv_timeout) do |
||||
{:ok, %HTTPoison.Response{status_code: status, body: body}} -> |
||||
{Helper.decode_json(body), status} |
||||
|
||||
{:error, reason} -> |
||||
Logger.error(fn -> |
||||
["Error while requesting XName app API endpoint #{url}. The reason is: ", inspect(reason)] |
||||
end) |
||||
|
||||
{nil, 500} |
||||
end |
||||
end |
||||
|
||||
@doc """ |
||||
https://gateway.xname.app/xhs/level/:address_hash endpoint |
||||
""" |
||||
@spec address_url(String.t()) :: String.t() |
||||
def address_url(address_hash_string) do |
||||
"#{base_url()}/xhs/level/#{address_hash_string}" |
||||
end |
||||
|
||||
defp base_url do |
||||
Microservice.base_url(__MODULE__) |
||||
end |
||||
|
||||
defp api_key do |
||||
Application.get_env(:explorer, __MODULE__)[:api_key] |
||||
end |
||||
end |
Loading…
Reference in new issue