aboutsummaryrefslogtreecommitdiffhomepage
path: root/frontend/app/routes/golf.$gameId.watch.tsx
blob: c2e269e46cd38e0d0febb5587f27bccbec781ba8 (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
65
66
67
68
69
70
import type { LoaderFunctionArgs, MetaFunction } from "@remix-run/node";
import { useLoaderData } from "@remix-run/react";
import { ClientOnly } from "remix-utils/client-only";
import { isAuthenticated } from "../.server/auth";
import { apiClient } from "../.server/api/client";
import GolfWatchApp from "../components/GolfWatchApp.client";
import GolfWatchAppConnecting from "../components/GolfWatchApps/GolfWatchAppConnecting";

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

  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 (
    <ClientOnly fallback={<GolfWatchAppConnecting />}>
      {() => <GolfWatchApp game={game} sockToken={sockToken} />}
    </ClientOnly>
  );
}