diff --git a/lib/entity.ex b/lib/entity.ex index f199583..c0dcd1c 100755 --- a/lib/entity.ex +++ b/lib/entity.ex @@ -2,10 +2,9 @@ defprotocol HTTPact.Entity do @moduledoc """ Provides a contract for an API Wrapper to convert responses into a return type. """ - @fallback_to_any true - def from_response(response) + def from_response(source_command, response) end -defimpl HTTPact.Entity, for: Any do - def from_response(response), do: response +defimpl HTTPact.Entity, for: HTTPact.Request do + def from_response(%HTTPact.Request{}, response), do: response end diff --git a/lib/httpact.ex b/lib/httpact.ex index ea21de8..14e272d 100755 --- a/lib/httpact.ex +++ b/lib/httpact.ex @@ -23,18 +23,28 @@ defmodule HTTPact do @spec execute(Request.t() | command(), http_client()) :: any def execute(%Request{} = request, client) when is_function(client) do - client.(request) - |> Entity.from_response() + with {:ok, response} <- client.(request) do + Entity.from_response(request, response) + else + {:error, _msg} = error -> error + :error -> {:error, "An unknown error occurred with the given HTTPact client"} + end end def execute(%Request{} = request, client) when is_atom(client) do - client.execute(request) - |> Entity.from_response() + with {:ok, response} <- client.execute(request) do + Entity.from_response(request, response) + else + {:error, _msg} = error -> error + :error -> {:error, "An unknown error occurred with the client: #{Atom.to_string(client)}"} + end end def execute(command, client) do - Command.to_request(command) - |> execute(client) - |> Entity.from_response() + response = + Command.to_request(command) + |> execute(client) + + Entity.from_response(command, response) end end diff --git a/test/httpact_test.exs b/test/httpact_test.exs index c426a39..1833ee1 100755 --- a/test/httpact_test.exs +++ b/test/httpact_test.exs @@ -1,7 +1,7 @@ defmodule HTTPactTest do use ExUnit.Case doctest HTTPact - HTTPact.{Request, Response} + alias HTTPact.{Request, Response} test "We can mock an HTTP Client with anonymous functions for testing API Wrappers" do # Build a function that knows how to return responses from matched requests @@ -23,17 +23,12 @@ defmodule HTTPactTest do body: "test body", path: "https://testsite.test/tests", headers: [{"test", "header"}], - http_client: test_client, } - assert HTTPact.execute(request) == {:ok, %Response{ + assert HTTPact.execute(request, test_client) == %Response{ status: 200, body: "it's kind of alive!", headers: [{"test", "header"}], - }} - end - - test "We can test an HTTP Client implementation by setting up a simple test server" do - assert false + } end end