diff options
author | Hubert Chathi <hubert@uhoreg.ca> | 2020-05-09 11:03:08 -0400 |
---|---|---|
committer | Hubert Chathi <hubert@uhoreg.ca> | 2020-05-09 11:03:08 -0400 |
commit | 654920f4419edef75757e14a9f9aa6c6a0f3ba41 (patch) | |
tree | 1f89c2bd726f0d0e50b7c2ca936e94884a9d2875 /lib/polyjuice/client/endpoint.ex | |
parent | release 0.2.2 (diff) |
parse errors and reduce code duplication
Diffstat (limited to 'lib/polyjuice/client/endpoint.ex')
-rw-r--r-- | lib/polyjuice/client/endpoint.ex | 34 |
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 |