Transformation: Convert Response

Learn the transformation of response and application configuration.

Convert the response

We’ll need a JSON library to convert the response into a data structure. Searching hex.pm, we found the poison library (no relation to HTTPoison), so let’s add its dependency to our mix.exs file.

defp deps do 
  [
    { :httpoison, "~> 1.0.0" },
    { :poison, "~> 3.1" }, 
  ]
end

If we run mix deps.get, we’ll end up with poison installed.

Next, we convert the body from a string. When we return the message from the GitHub API in gitHub_issues.ex file, we call the Poison.Parser.parse! function as seen below:

def handle_response({ _, %{status_code: status_code, body: body}}) do {
    status_code |> check_for_error(),
    body        |> Poison.Parser.parse!()
  }
end
defp check_for_error(200), do: :ok
defp check_for_error(_), do: :error

We also have to deal with a possible error response from the fetch. So, back in the CLI module, we write a function that decodes the body and returns it on a success response. The function extracts the error from the body and displays it otherwise.

def process({user, project, _count}) do
    Issues.GithubIssues.fetch(user, project)
    |> decode_response()
  end

  def decode_response({:ok, body}), do: body

  def decode_response({:error, error}) do
    IO.puts "Error fetching from Github: #{error["message"]}"
    System.halt(2)
  end

The JSON that GitHub returns for a successful response is a list of maps, where each map in the list contains a GitHub issue.

We can experiment with the complete code above in the following terminal:

Get hands-on with 1400+ tech skills courses.