Skip to content

Commit 2491d6f

Browse files
committed
Code for step 6
1 parent ccfe4fa commit 2491d6f

File tree

2 files changed

+66
-1
lines changed

2 files changed

+66
-1
lines changed

lib/elixir_popularity/application.ex

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,8 @@ defmodule ElixirPopularity.Application do
2727
}
2828
]},
2929
restart: :transient
30-
}
30+
},
31+
ElixirPopularity.HackernewsIdProcessor
3132
]
3233

3334
# See https://hexdocs.pm/elixir/Supervisor.html

lib/hackernews_id_processor.ex

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
defmodule ElixirPopularity.HackernewsIdProcessor do
2+
use Broadway
3+
4+
alias Broadway.Message
5+
alias ElixirPopularity.{HackernewsApi, RMQPublisher}
6+
7+
def start_link(_opts) do
8+
Broadway.start_link(__MODULE__,
9+
name: __MODULE__,
10+
producers: [
11+
default: [
12+
module:
13+
{BroadwayRabbitMQ.Producer,
14+
queue: RMQPublisher.item_id_queue_name(),
15+
connection: [
16+
username: "rabbitmq",
17+
password: "rabbitmq"
18+
]},
19+
stages: 1
20+
]
21+
],
22+
processors: [
23+
default: [
24+
stages: 100
25+
]
26+
],
27+
batchers: [
28+
default: [
29+
batch_size: 10,
30+
batch_timeout: 10_000,
31+
stages: 2
32+
]
33+
]
34+
)
35+
end
36+
37+
@impl true
38+
def handle_message(_processor, message, _context) do
39+
Message.update_data(message, fn hn_id ->
40+
{hn_id, HackernewsApi.get_hn_item(hn_id)}
41+
end)
42+
end
43+
44+
@impl true
45+
def handle_batch(_batcher, messages, _batch_info, _context) do
46+
encoded_payload =
47+
messages
48+
|> Enum.reject(fn
49+
%Message{data: {_id, :error}} -> true
50+
_ -> false
51+
end)
52+
|> Enum.map(fn %Message{data: {id, item}} ->
53+
%{
54+
id: id,
55+
item: Map.from_struct(item)
56+
}
57+
end)
58+
|> Jason.encode!()
59+
60+
RMQPublisher.publish_hn_items(encoded_payload)
61+
62+
messages
63+
end
64+
end

0 commit comments

Comments
 (0)