Skip to content

Commit

Permalink
Code for step 3
Browse files Browse the repository at this point in the history
  • Loading branch information
akoutmos committed Nov 11, 2019
1 parent caa7087 commit c059d20
Show file tree
Hide file tree
Showing 3 changed files with 86 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/elixir_popularity/application.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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
]

Expand Down
63 changes: 63 additions & 0 deletions lib/hackernews_api.ex
Original file line number Diff line number Diff line change
@@ -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
22 changes: 22 additions & 0 deletions lib/hackernews_item.ex
Original file line number Diff line number Diff line change
@@ -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.