@@ -5,36 +5,50 @@ defmodule Bob.DockerHub.Pager do
55 @ timeout 60 * 60 * 1000
66
77 def start_link ( url ) do
8- GenServer . start_link ( __MODULE__ , url )
8+ GenServer . start_link ( __MODULE__ , { url , nil } )
9+ end
10+
11+ def start_link ( url , on_result ) do
12+ GenServer . start_link ( __MODULE__ , { url , on_result } )
913 end
1014
1115 def wait ( server ) do
1216 GenServer . call ( server , :wait , @ timeout )
1317 end
1418
15- def init ( url ) do
16- { :ok , next_request ( % { url: url , page: 1 , tasks: MapSet . new ( ) , results: [ ] , reply: nil } ) }
19+ def init ( { url , on_result } ) do
20+ { :ok , next_request ( % { url: url , on_result: on_result , page: 1 , tasks: MapSet . new ( ) , results: [ ] , reply: nil } ) }
1721 end
1822
1923 def handle_call ( :wait , from , state ) do
2024 if MapSet . size ( state . tasks ) == 0 do
21- { :stop , :normal , Enum . concat ( state . results ) , state }
25+ result = if state . on_result , do: :ok , else: Enum . concat ( state . results )
26+ { :stop , :normal , result , state }
2227 else
2328 state = % { state | reply: from }
2429 { :noreply , state }
2530 end
2631 end
2732
2833 def handle_info ( { ref , { :ok , result } } , state ) do
29- state = % { state | tasks: MapSet . delete ( state . tasks , ref ) , results: [ result | state . results ] }
34+ state =
35+ if state . on_result do
36+ state . on_result . ( result )
37+ state
38+ else
39+ % { state | results: [ result | state . results ] }
40+ end
41+
42+ state = % { state | tasks: MapSet . delete ( state . tasks , ref ) }
3043 { :noreply , next_request ( state ) }
3144 end
3245
3346 def handle_info ( { ref , :done } , state ) do
3447 state = % { state | tasks: MapSet . delete ( state . tasks , ref ) }
3548
3649 if MapSet . size ( state . tasks ) == 0 do
37- GenServer . reply ( state . reply , Enum . concat ( state . results ) )
50+ result = if state . on_result , do: :ok , else: Enum . concat ( state . results )
51+ GenServer . reply ( state . reply , result )
3852 { :stop , :normal , state }
3953 else
4054 { :noreply , state }
@@ -60,8 +74,8 @@ defmodule Bob.DockerHub.Pager do
6074
6175 case result do
6276 { :ok , 200 , _headers , body } ->
63- body = Jason . decode! ( body )
64- { :ok , Enum . flat_map ( body [ "results" ] , & List . wrap ( Bob.DockerHub . parse ( & 1 ) ) ) }
77+ { decoded , _ , _ } = :json . decode ( body )
78+ { :ok , Enum . flat_map ( decoded [ "results" ] , & List . wrap ( Bob.DockerHub . parse ( & 1 ) ) ) }
6579
6680 { :ok , 404 , _headers , _body } ->
6781 :done
0 commit comments