geo-therminator/lib/geo_therminator/pump_api/http.ex
2021-11-07 11:01:39 +02:00

49 lines
1.3 KiB
Elixir

defmodule GeoTherminator.PumpAPI.HTTP do
@spec authed_req(
GeoTherminator.PumpAPI.Auth.User.t(),
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
|> List.keystore("authorization", 0, {"authorization", "Bearer #{user.token.token}"})
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