aboutsummaryrefslogtreecommitdiffhomepage
path: root/frontend/app/routes/golf.$gameId.watch.tsx
blob: 40932958bfa3a8cf552612a3780e32fbe1545d34 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import type { LoaderFunctionArgs, MetaFunction } from "@remix-run/node";
import { isAuthenticated } from "../.server/auth";
import { apiClient } from "../.server/api/client";
import { useLoaderData } from "@remix-run/react";
import GolfWatchApp from "../components/GolfWatchApp";

export const meta: MetaFunction<typeof loader> = ({ data }) => {
  return [
    {
      title: data
        ? `Golf Watching ${data.game.display_name} | iOSDC 2024 Albatross.swift`
        : "Golf Watching | iOSDC 2024 Albatross.swift",
    },
  ];
};

export async function loader({ params, request }: LoaderFunctionArgs) {
  const { token } = await isAuthenticated(request, {
    failureRedirect: "/login",
  });

  const fetchGame = async () => {
    const { data, error } = await apiClient.GET("/games/{game_id}", {
      params: {
        path: {
          game_id: Number(params.gameId),
        },
        header: {
          Authorization: `Bearer ${token}`,
        },
      },
    });
    if (error) {
      throw new Error(error.message);
    }
    return data;
  };

  const fetchSockToken = async () => {
    const { data, error } = await apiClient.GET("/token", {
      params: {
        header: {
          Authorization: `Bearer ${token}`,
        },
      },
    });
    if (error) {
      throw new Error(error.message);
    }
    return data.token;
  };

  const [game, sockToken] = await Promise.all([fetchGame(), fetchSockToken()]);
  return {
    game,
    sockToken,
  };
}

export default function GolfWatch() {
  const { game, sockToken } = useLoaderData<typeof loader>();

  return <GolfWatchApp game={game} sockToken={sockToken} />;
}