Simple error processing
This commit is contained in:
@@ -69,29 +69,34 @@ defmodule MicrosoftTranslator.Client do
|
||||
|
||||
defp parse(%{body: body}, api_method) do
|
||||
Jason.decode!(body, keys: :atoms)
|
||||
|> transform_response(api_method)
|
||||
|> process_response(api_method)
|
||||
end
|
||||
|
||||
defp transform_response(response, :detect) do
|
||||
result =
|
||||
response
|
||||
|> List.first()
|
||||
|> Map.fetch(:language)
|
||||
defp process_response(response, api_method) do
|
||||
case response do
|
||||
%{error: %{code: code, message: message}} ->
|
||||
%{error: %{code: code, message: message}}
|
||||
|
||||
case result do
|
||||
list when is_list(list) and api_method in ~w(detect translate)a ->
|
||||
list
|
||||
|> List.first()
|
||||
|> transform_response(api_method)
|
||||
|
||||
map when is_map(map) and api_method in ~w(languages)a ->
|
||||
transform_response(map, api_method)
|
||||
end
|
||||
end
|
||||
|
||||
defp transform_response(response, :detect) when is_map(response) do
|
||||
case Map.fetch(response, :language) do
|
||||
{:ok, language} -> %{languageCode: language}
|
||||
end
|
||||
end
|
||||
|
||||
defp transform_response(response, :translate) do
|
||||
response
|
||||
|> List.first()
|
||||
|> Map.take([:translations])
|
||||
end
|
||||
|
||||
defp transform_response(response, :languages) do
|
||||
%{dictionary: dictionary} = response
|
||||
defp transform_response(response, :translate) when is_map(response),
|
||||
do: Map.take(response, ~w(translations)a)
|
||||
|
||||
defp transform_response(%{dictionary: dictionary}, :languages) do
|
||||
dictionary
|
||||
|> Enum.map(fn {key, %{name: name, nativeName: native, dir: dir}} ->
|
||||
%{code: "#{key}", name: name, nativeName: native, dir: dir}
|
||||
|
||||
Reference in New Issue
Block a user