rename to getGame & improve error handling

This commit is contained in:
Nathaniel Tampus
2023-03-05 00:33:44 +08:00
parent 997cbacc66
commit b7ee6f4371
2 changed files with 31 additions and 20 deletions

View File

@@ -3,7 +3,7 @@
import type { FormEvent } from "react"; import type { FormEvent } from "react";
import { useState, useContext } from "react"; import { useState, useContext } from "react";
import { SessionContext } from "@/context/session"; import { SessionContext } from "@/context/session";
import { findGame } from "@/lib/game"; import { getGame } from "@/lib/game";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
export default function JoinGame() { export default function JoinGame() {
@@ -24,7 +24,7 @@ export default function JoinGame() {
code = new URL(code).pathname.split("/")[2]; code = new URL(code).pathname.split("/")[2];
} }
const game = await findGame(code); const game = await getGame(code);
if (game) { if (game) {
router.push(`/game/${game.code}`); router.push(`/game/${game.code}`);

View File

@@ -2,24 +2,35 @@ import type { Game } from "@chessu/types";
import { API_URL } from "@/config"; import { API_URL } from "@/config";
export const createGame = async (side: string, unlisted: boolean) => { export const createGame = async (side: string, unlisted: boolean) => {
const res = await fetch(`${API_URL}/v1/games`, { try {
method: "POST", const res = await fetch(`${API_URL}/v1/games`, {
credentials: "include", method: "POST",
headers: { credentials: "include",
"Content-Type": "application/json" headers: {
}, "Content-Type": "application/json"
body: JSON.stringify({ side, unlisted }) },
}); body: JSON.stringify({ side, unlisted }),
cache: "no-store"
});
const game: Game | undefined = await res.json(); if (res && res.status === 201) {
return game; const game: Game = await res.json();
}; return game;
}
export const findGame = async (code: string) => { } catch (err) {
const res = await fetch(`${API_URL}/v1/games/${code}`); console.error(err);
}
if (res && res.status === 200) { };
const game: Game = await res.json();
return game; export const getGame = async (code: string) => {
try {
const res = await fetch(`${API_URL}/v1/games/${code}`, { cache: "no-store" });
if (res && res.status === 200) {
const game: Game = await res.json();
return game;
}
} catch (err) {
console.error(err);
} }
}; };