Packages

SDK de integração Bry

Current section

Files

Jump to
bry lib request.ex
Raw

lib/request.ex

defmodule BrySdkElixir.Request do
@moduledoc false
def headers do
[{"Content-Type", "application/json"}]
end
def opt do
[timeout: 100_000, recv_timeout: 100_000]
end
def auth do
body = {:form, [
{:grant_type, "client_credentials"},
{:client_id, Application.get_env(:bry_sdk_elixir, :client_id) || System.get_env("client_id")},
{:client_secret, Application.get_env(:bry_sdk_elixir, :client_secret) || System.get_env("client_secret")}
]}
headers = [{"Content-Type", "application/x-www-form-urlencoded"}]
HTTPoison.post("https://cloud.bry.com.br/token-service/jwt", body, headers)
|> parse_response()
end
def access_header do
with {:ok, tokens} <- auth() do
{:ok, {"Authorization", "Bearer #{tokens.access_token}"}}
end
end
def get(url) do
with {:ok, token} <- access_header() do
HTTPoison.get("#{url}", [token | headers()], opt())
|> debug()
|> parse_response()
end
end
def post(url, data, custom_header) do
with {:ok, token} <- access_header(),
custom_headers <- [token] ++ custom_header ++ headers() |> List.flatten() do
HTTPoison.post("#{url}", Jason.encode!(data), custom_headers, opt())
|> debug()
|> parse_response()
end
end
def put(url, data) do
with {:ok, token} <- access_header() do
HTTPoison.put("#{url}", Jason.encode!(data), [token | headers()], opt())
|> debug()
|> parse_response()
end
end
def delete(url) do
with {:ok, token} <- access_header() do
HTTPoison.delete("#{url}", [token | headers()], opt())
|> debug()
|> parse_response()
end
end
def debug(request) do
IO.inspect(request)
if Application.get_env(:bry_sdk_elixir, :debug) do
end
request
end
def parse_response(request) do
case request do
{:ok, %HTTPoison.Response{status_code: 200, body: body}} ->
{:ok, Jason.decode!(body, keys: :atoms)}
{:ok, %HTTPoison.Response{status_code: 500, body: body}} ->
{:error, Jason.decode!(body, keys: :atoms)}
{:ok, %HTTPoison.Response{status_code: 404}} ->
{:error, 404}
{:error, %HTTPoison.Error{reason: reason}} ->
{:error, reason}
end
end
end