Skip to content

Instantly share code, notes, and snippets.

@syamilmj
Created December 15, 2016 09:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save syamilmj/915e7635d6808f9e53e440a0e8a50eb2 to your computer and use it in GitHub Desktop.
Save syamilmj/915e7635d6808f9e53e440a0e8a50eb2 to your computer and use it in GitHub Desktop.
HTTP Client base
defmodule Crux.Http do
use HTTPoison.Base
def process_url(url) do
Application.get_env(:crux, :api) <> url
end
def process_request_body(body) when is_map(body) do
Poison.encode!(body)
end
def process_request_body(body), do: body
def process_request_headers(headers) do
defaults = [{"Content-Type", "application/json"}, {"Accept", "application/json"}]
defaults ++ headers
end
def process_response_body(body) do
Poison.Parser.parse!(body, keys: :atoms)
end
def parse(response, key) do
response.body |> Map.get(key)
end
def set_authentication_cookie(cookie) do
[{"Cookie", "_kfit-app_session_ar=#{cookie}"}]
end
defmacro endpoint(url) do
{params, _segments} = Plug.Router.Utils.build_path_match(url)
params =
Enum.map(params, fn(x) -> Atom.to_string(x) end)
|> Enum.join(",")
|> (&Code.string_to_quoted!("[#{&1}]")).()
quote do
def path(unquote_splicing(params)) do
String.split(unquote(url), "/", trim: true)
|> Enum.reduce({0, ""}, fn(piece, {index, acc}) ->
case piece do
":" <> _arg ->
acc = acc <> "/" <> Enum.at(unquote(params), index)
{index + 1, acc}
str ->
{index, acc <> "/" <> str}
end
end)
|> elem(1)
end
end
end
defmacro __using__(_) do
quote do
import Crux.Http
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment