Skip to content

Instantly share code, notes, and snippets.

@abhiche
Created January 13, 2021 06:04
Show Gist options
  • Save abhiche/d7b8232238fe4616670e168c6292b24c to your computer and use it in GitHub Desktop.
Save abhiche/d7b8232238fe4616670e168c6292b24c to your computer and use it in GitHub Desktop.
defmodule MyApp.HTTPClient do
@moduledoc """
This module should be used to make http requests
"""
require Logger
require OK
defp decode_json(body) do
case Jason.decode(body) do
{:ok, decoded} -> decoded
{:error, %Jason.DecodeError{data: data}} -> data
end
end
defp decode_body(
{:ok, %HTTPoison.Response{status_code: status_code, body: body, headers: headers}}
) do
case Enum.member?(headers, {"Content-Type", "application/json"}) or
Enum.member?(headers, {"Content-Type", "application/json; charset=utf-8"}) do
true ->
{status_code, decode_json(body)}
_ ->
{status_code, body}
end
end
defp decode_body({:ok, %HTTPoison.Response{status_code: status_code}}) do
{status_code, ""}
end
defp decode_body({:error, %HTTPoison.Error{reason: reason}}) do
{:error, reason}
end
defp format_response({:error, reason}) do
{:error, reason}
end
defp format_response({status_code, body}) when status_code >= 200 and status_code < 400 do
{:ok, body}
end
defp format_response({status_code, body}) when status_code >= 400 do
{:error, body}
end
defp do_post(url, payload, headers) do
HTTPoison.post(url, payload, headers) |> decode_body |> format_response
end
defp do_get(url, headers, options) do
HTTPoison.get(url, headers, options) |> decode_body |> format_response
end
def get(nil, _headers, _options), do: {:error, :missing_url}
def get(url, headers, options) do
do_get(url, headers, options)
end
def post(nil, _payload, _headers), do: {:error, :missing_url}
def post(url, payload, headers) do
do_post(url, payload, headers)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment