@@ -5,46 +5,51 @@ defmodule CodebattleWeb.ExtApi.TournamentController do
55
66 plug ( CodebattleWeb.Plugs.TokenAuth )
77
8- # Define the JSON file paths
9- @ json_files [
10- "/json/tournament_state_round1.json" ,
11- "/json/tournament_state_round2.json" ,
12- "/json/tournament_state_round3.json" ,
13- "/json/tournament_state_round4.json" ,
14- "/json/tournament_state_round5.json" ,
15- "/json/tournament_state_round6.json" ,
16- "/json/tournament_state_round7.json"
17- ]
18-
19- # Use an Agent to store the current index
20- def start_link do
21- Agent . start_link ( fn -> 0 end , name: __MODULE__ )
22- end
23-
24- # Initialize the Agent when the application starts
25- def init do
26- if ! Process . whereis ( __MODULE__ ) , do: start_link ( )
27- end
28-
29- def show ( conn , % { "base_url" => base_url } = _params ) do
30- # Initialize the agent if it doesn't exist
31- init ( )
32-
33- # Get current index and update it for the next request
34- current_index =
35- Agent . get_and_update ( __MODULE__ , fn index ->
36- next_index = rem ( index + 1 , length ( @ json_files ) )
37- { index , next_index }
8+ @ json_files ~w(
9+ /json/tournament_state_round1.json
10+ /json/tournament_state_round2.json
11+ /json/tournament_state_round3.json
12+ /json/tournament_state_round4.json
13+ /json/tournament_state_round5.json
14+ /json/tournament_state_round6.json
15+ /json/tournament_state_round7.json
16+ )
17+
18+ # -------------------------------------------------
19+ # Simple in-memory index so every call rotates file
20+ # -------------------------------------------------
21+ def start_link , do: Agent . start_link ( fn -> 0 end , name: __MODULE__ )
22+ defp ensure_agent_started , do: Process . whereis ( __MODULE__ ) || start_link ( )
23+
24+ # ---------------
25+ # GET /ext_api...
26+ # ---------------
27+ def show ( conn , % { "base_url" => base_url } ) do
28+ ensure_agent_started ( )
29+
30+ idx =
31+ Agent . get_and_update ( __MODULE__ , fn i ->
32+ { i , rem ( i + 1 , length ( @ json_files ) ) }
3833 end )
3934
40- # Get the current JSON file path
41- json_path = Enum . at ( @ json_files , current_index )
35+ url = base_url <> Enum . at ( @ json_files , idx )
36+
37+ case Req . get ( url , decode_body: false ) do
38+ { :ok , % { status: 200 , body: body } } ->
39+ conn
40+ |> put_resp_content_type ( "application/json" )
41+ |> send_resp ( 200 , body )
4242
43- # Construct the full URL
44- redirect_url = "#{ base_url } #{ json_path } "
43+ { :ok , % { status: status } } ->
44+ conn
45+ |> put_status ( :bad_gateway )
46+ |> json ( % { error: "Failed to retrieve JSON" , status: status } )
4547
46- # Redirect to the S3 bucket URL
47- redirect ( conn , external: redirect_url )
48+ { :error , reason } ->
49+ conn
50+ |> put_status ( :internal_server_error )
51+ |> json ( % { error: "Error fetching JSON: #{ inspect ( reason ) } " } )
52+ end
4853 end
4954
5055 def show ( conn , _params ) do
0 commit comments