summaryrefslogtreecommitdiff
path: root/lib/polyjuice/client/endpoint.ex
diff options
context:
space:
mode:
Diffstat (limited to 'lib/polyjuice/client/endpoint.ex')
-rw-r--r--lib/polyjuice/client/endpoint.ex34
1 files changed, 34 insertions, 0 deletions
diff --git a/lib/polyjuice/client/endpoint.ex b/lib/polyjuice/client/endpoint.ex
index 1b6b7b5..f6c8247 100644
--- a/lib/polyjuice/client/endpoint.ex
+++ b/lib/polyjuice/client/endpoint.ex
@@ -68,4 +68,38 @@ defmodule Polyjuice.Client.Endpoint do
) :: any
def transform_http_result(endpoint_args, status_code, headers, body)
end
+
+ defprotocol BodyParser do
+ @fallback_to_any true
+ @spec parse(endpoint_args :: __MODULE__.t(), body :: any) :: {:ok, any} | any
+ def parse(endpoint_args, body)
+ end
+
+ defimpl BodyParser, for: Any do
+ def parse(_endpoint_args, body), do: {:ok, body}
+ end
+
+ @spec parse_response(
+ endpoint_args :: map,
+ status_code :: integer(),
+ headers :: [{String.t(), String.t()}, ...],
+ body :: String.t()
+ ) :: {:ok, any} | any
+ def parse_response(%{} = endpoint_args, status_code, headers, body)
+ when is_integer(status_code) and is_list(headers) and is_binary(body) do
+ # FIXME: check if content type is "application/json"
+ with {:ok, json} <- Poison.decode(body) do
+ case status_code do
+ 200 ->
+ Polyjuice.Client.Endpoint.BodyParser.parse(endpoint_args, json)
+
+ _ ->
+ {:error, status_code, json}
+ end
+ else
+ _ ->
+ {:error, if(status_code == 200, do: 500, else: status_code),
+ %{"errcode" => "CA_UHOREG_POLYJUICE_BAD_RESPONSE", "body" => body}}
+ end
+ end
end