defmodule GeoTherminator.PumpAPI.HTTP do require GeoTherminator.PumpAPI.Auth.User require GeoTherminator.PumpAPI.Auth.Tokens alias GeoTherminator.PumpAPI.Auth.User alias GeoTherminator.PumpAPI.Auth.Tokens @spec authed_req( 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.record(user, :tokens) |> Tokens.record(:access_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