Skip to content
Permalink
Browse files

Code for step 3

  • Loading branch information
akoutmos committed Nov 11, 2019
1 parent caa7087 commit c059d201d9d30fdd7dd8f9a3bafd6a17cfb56b13
Showing with 86 additions and 0 deletions.
  1. +1 −0 lib/elixir_popularity/application.ex
  2. +63 −0 lib/hackernews_api.ex
  3. +22 −0 lib/hackernews_item.ex
@@ -7,6 +7,7 @@ defmodule ElixirPopularity.Application do

def start(_type, _args) do
children = [
:hackney_pool.child_spec(:hn_id_pool, timeout: 15000, max_connections: 100),
ElixirPopularity.Repo
]

@@ -0,0 +1,63 @@
defmodule ElixirPopularity.HackernewsApi do
@moduledoc """
Fetches data from the Hackernews API, extracts the necessary fields,
and massages some data
"""

require Logger

alias ElixirPopularity.HackernewsItem

def get_hn_item(resource_id) do
get_hn_item(resource_id, 4)
end

defp get_hn_item(resource_id, retry) do
response =
resource_id
|> gen_api_url()
|> HTTPoison.get([], hackney: [pool: :hn_id_pool])

with {_, {:ok, body}} <- {"hn_api", handle_response(response)},
{_, {:ok, decoded_payload}} <- {"payload_decode", Jason.decode(body)},
{_, {:ok, data}} <- {"massage_data", massage_data(decoded_payload)} do
data
else
{stage, error} ->
Logger.warn(
"Failed attempt #{5 - retry} at stage \"#{stage}\" with Hackernews ID of #{resource_id}. Error details: #{
inspect(error)
}"
)

if retry > 0 do
get_hn_item(resource_id, retry - 1)
else
Logger.warn("Failed to retrieve Hackernews ID of #{resource_id}.")
:error
end
end
end

defp handle_response({:ok, %HTTPoison.Response{status_code: 200, body: body}}) do
{:ok, body}
end

defp handle_response({_, invalid_response}) do
{:error, invalid_response}
end

defp gen_api_url(resource_id) do
"https://hacker-news.firebaseio.com/v0/item/#{resource_id}.json"
end

defp massage_data(data) do
{:ok,
HackernewsItem.create(
data["text"],
data["type"],
data["title"],
data["time"]
)}
end
end
@@ -0,0 +1,22 @@
defmodule ElixirPopularity.HackernewsItem do
alias __MODULE__

defstruct text: nil, type: nil, title: nil, time: nil

def create(text, type, title, unix_time) do
%HackernewsItem{
text: text,
type: type,
title: title,
time: get_date_time(unix_time)
}
end

defp get_date_time(nil), do: nil

defp get_date_time(unix_time) do
{:ok, date_time} = DateTime.from_unix(unix_time)

DateTime.to_date(date_time)
end
end

0 comments on commit c059d20

Please sign in to comment.
You can’t perform that action at this time.