Skip to content

Commit c059d20

Browse files
committed
Code for step 3
1 parent caa7087 commit c059d20

File tree

3 files changed

+86
-0
lines changed

3 files changed

+86
-0
lines changed

lib/elixir_popularity/application.ex

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ defmodule ElixirPopularity.Application do
77

88
def start(_type, _args) do
99
children = [
10+
:hackney_pool.child_spec(:hn_id_pool, timeout: 15000, max_connections: 100),
1011
ElixirPopularity.Repo
1112
]
1213

lib/hackernews_api.ex

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
defmodule ElixirPopularity.HackernewsApi do
2+
@moduledoc """
3+
Fetches data from the Hackernews API, extracts the necessary fields,
4+
and massages some data
5+
"""
6+
7+
require Logger
8+
9+
alias ElixirPopularity.HackernewsItem
10+
11+
def get_hn_item(resource_id) do
12+
get_hn_item(resource_id, 4)
13+
end
14+
15+
defp get_hn_item(resource_id, retry) do
16+
response =
17+
resource_id
18+
|> gen_api_url()
19+
|> HTTPoison.get([], hackney: [pool: :hn_id_pool])
20+
21+
with {_, {:ok, body}} <- {"hn_api", handle_response(response)},
22+
{_, {:ok, decoded_payload}} <- {"payload_decode", Jason.decode(body)},
23+
{_, {:ok, data}} <- {"massage_data", massage_data(decoded_payload)} do
24+
data
25+
else
26+
{stage, error} ->
27+
Logger.warn(
28+
"Failed attempt #{5 - retry} at stage \"#{stage}\" with Hackernews ID of #{resource_id}. Error details: #{
29+
inspect(error)
30+
}"
31+
)
32+
33+
if retry > 0 do
34+
get_hn_item(resource_id, retry - 1)
35+
else
36+
Logger.warn("Failed to retrieve Hackernews ID of #{resource_id}.")
37+
:error
38+
end
39+
end
40+
end
41+
42+
defp handle_response({:ok, %HTTPoison.Response{status_code: 200, body: body}}) do
43+
{:ok, body}
44+
end
45+
46+
defp handle_response({_, invalid_response}) do
47+
{:error, invalid_response}
48+
end
49+
50+
defp gen_api_url(resource_id) do
51+
"https://hacker-news.firebaseio.com/v0/item/#{resource_id}.json"
52+
end
53+
54+
defp massage_data(data) do
55+
{:ok,
56+
HackernewsItem.create(
57+
data["text"],
58+
data["type"],
59+
data["title"],
60+
data["time"]
61+
)}
62+
end
63+
end

lib/hackernews_item.ex

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
defmodule ElixirPopularity.HackernewsItem do
2+
alias __MODULE__
3+
4+
defstruct text: nil, type: nil, title: nil, time: nil
5+
6+
def create(text, type, title, unix_time) do
7+
%HackernewsItem{
8+
text: text,
9+
type: type,
10+
title: title,
11+
time: get_date_time(unix_time)
12+
}
13+
end
14+
15+
defp get_date_time(nil), do: nil
16+
17+
defp get_date_time(unix_time) do
18+
{:ok, date_time} = DateTime.from_unix(unix_time)
19+
20+
DateTime.to_date(date_time)
21+
end
22+
end

0 commit comments

Comments
 (0)