geo-therminator/lib/geo_therminator/pump_api/http.ex

60 lines
1.5 KiB
Elixir
Raw Normal View History

2021-11-07 09:01:39 +00:00
defmodule GeoTherminator.PumpAPI.HTTP do
2023-01-11 18:37:27 +00:00
require GeoTherminator.PumpAPI.Auth.User
require GeoTherminator.PumpAPI.Auth.Tokens
alias GeoTherminator.PumpAPI.Auth.User
alias GeoTherminator.PumpAPI.Auth.Tokens
2021-11-07 09:01:39 +00:00
@spec authed_req(
2023-01-11 18:37:27 +00:00
User.t(),
2021-11-07 09:01:39 +00:00
Finch.Request.method(),
Finch.Request.url(),
Finch.Request.headers(),
map() | nil,
Keyword.t()
) ::
Finch.Request.t()
def authed_req(user, method, url, headers \\ [], body \\ nil, opts \\ []) do
headers =
headers
2023-01-11 18:37:27 +00:00
|> List.keystore(
"authorization",
0,
{"authorization", "Bearer #{User.record(user, :tokens) |> Tokens.record(:access_token)}"}
)
2021-11-07 09:01:39 +00:00
req(method, url, headers, body, opts)
end
@spec req(
Finch.Request.method(),
Finch.Request.url(),
Finch.Request.headers(),
map() | nil,
Keyword.t()
) ::
Finch.Request.t()
def req(method, url, headers \\ [], body \\ nil, opts \\ []) do
headers =
headers
|> List.keystore("accept", 0, {"accept", "application/json"})
headers =
if not is_nil(body) do
List.keystore(headers, "content-type", 0, {"content-type", "application/json"})
else
headers
end
opts = Keyword.put(opts, :timeout, Application.get_env(:geo_therminator, :api_timeout))
Finch.build(
method,
url,
headers,
if(not is_nil(body), do: Jason.encode!(body)),
opts
)
end
end