Using Mojito instead Mint
This commit is contained in:
@@ -1,18 +1,17 @@
|
||||
defmodule MicrosoftTranslator.Client do
|
||||
@empty_state %{data: [], done: false}
|
||||
@base_host "api.cognitive.microsofttranslator.com"
|
||||
@base_path "/"
|
||||
@api_methods %{
|
||||
languages: %{
|
||||
method: "GET",
|
||||
method: :get,
|
||||
path: "languages"
|
||||
},
|
||||
detect: %{
|
||||
method: "POST",
|
||||
method: :post,
|
||||
path: "detect"
|
||||
},
|
||||
translate: %{
|
||||
method: "POST",
|
||||
method: :post,
|
||||
path: "translate"
|
||||
}
|
||||
}
|
||||
@@ -68,7 +67,7 @@ defmodule MicrosoftTranslator.Client do
|
||||
|
||||
defp transform_body(_, params), do: params
|
||||
|
||||
defp parse({:ok, %{data: body}}, api_method) do
|
||||
defp parse(%{body: body}, api_method) do
|
||||
Jason.decode!(body, keys: :atoms)
|
||||
|> transform_response(api_method)
|
||||
end
|
||||
@@ -101,49 +100,10 @@ defmodule MicrosoftTranslator.Client do
|
||||
|
||||
def fetch(api_method, headers, body, params) do
|
||||
method = @api_methods[api_method].method
|
||||
path = @base_path <> @api_methods[api_method].path <> params
|
||||
url = "https://#{@base_host}#{@base_path}#{@api_methods[api_method].path}#{params}"
|
||||
|
||||
with {:ok, conn} <- Mint.HTTP.connect(:https, @base_host, 443),
|
||||
{:ok, conn, _ref} <- Mint.HTTP.request(conn, method, path, headers, body) do
|
||||
handle_response(conn, @empty_state)
|
||||
end
|
||||
end
|
||||
{:ok, response} = Mojito.request(method, url, headers, body)
|
||||
|
||||
defp handle_response(conn, state) do
|
||||
receive do
|
||||
message ->
|
||||
case Mint.HTTP.stream(conn, message) do
|
||||
{:ok, conn, responses} ->
|
||||
case Enum.reduce(responses, state, &handle_res/2) do
|
||||
# Loop ends here
|
||||
%{done: true} = state -> {:ok, state}
|
||||
%{done: false} = state -> handle_response(conn, state)
|
||||
end
|
||||
|
||||
{:error, _, reason, _} ->
|
||||
{:error, reason}
|
||||
|
||||
:unknown ->
|
||||
{:unexpected, message}
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
defp handle_res({:status, _, status}, state),
|
||||
do: Map.put(state, :status, status)
|
||||
|
||||
defp handle_res({:headers, _, headers}, state),
|
||||
do: Map.put(state, :headers, headers)
|
||||
|
||||
defp handle_res({:data, _, data}, state),
|
||||
do: Map.update!(state, :data, fn acc -> [data | acc] end)
|
||||
|
||||
defp handle_res({:done, _}, state) do
|
||||
Map.update!(state, :data, fn acc ->
|
||||
acc
|
||||
|> Enum.reverse()
|
||||
|> Enum.join("")
|
||||
end)
|
||||
|> Map.put(:done, true)
|
||||
response
|
||||
end
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user