Skip to content

Commit

Permalink
improve error handling chess.com importer
Browse files Browse the repository at this point in the history
  • Loading branch information
franciscoBSalgueiro committed Sep 7, 2024
1 parent 61fc4ae commit e5b8ad0
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 10 deletions.
7 changes: 6 additions & 1 deletion src/components/tabs/ImportModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,12 @@ export default function ImportModal({
}
let pgn = "";
if (link.includes("chess.com")) {
pgn = await getChesscomGame(link);
const res = await getChesscomGame(link);
if (res === null) {
setLoading(false);
return;
}
pgn = res;
} else if (link.includes("lichess")) {
const gameId = link.split("/")[3];
pgn = await getLichessGame(gameId);
Expand Down
50 changes: 41 additions & 9 deletions src/utils/chess.com/api.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,11 @@ export async function downloadChessCom(
});
}

const chessComGameSchema = z.object({
moveList: z.string(),
pgnHeaders: z.record(z.string(), z.string()),
});

export async function getChesscomGame(gameURL: string) {
const regex = /.*\/game\/(live|daily)\/(\d+)/;
const match = gameURL.match(regex);
Expand All @@ -187,15 +192,42 @@ export async function getChesscomGame(gameURL: string) {
const gameType = match[1];
const gameId = match[2];

const apiData = await fetch<{
game: { moveList: string; pgnHeaders: Record<string, string | number> };
}>(`https://www.chess.com/callback/${gameType}/game/${gameId}`, {
headers,
method: "GET",
});
const apiDataJson = await apiData.data;
const moveList = apiDataJson.game.moveList;
const pgnHeaders = apiDataJson.game.pgnHeaders;
const response = await fetch(
`https://www.chess.com/callback/${gameType}/game/${gameId}`,
{
headers,
method: "GET",
},
);

if (!response.ok) {
error(`Failed to fetch Chess.com game: ${response.status} ${response.url}`);
notifications.show({
title: "Failed to fetch Chess.com game",
message: `Could not find game "${gameURL}" on chess.com`,
color: "red",
icon: <IconX />,
});
return null;
}

const apiData = await response.data;
const gameData = chessComGameSchema.safeParse(apiData);
if (!gameData.success) {
error(
`Invalid response for Chess.com game: ${response.status} ${response.url}\n${gameData.error}`,
);
notifications.show({
title: "Failed to fetch Chess.com game",
message: `Invalid response for "${gameURL}" on chess.com`,
color: "red",
icon: <IconX />,
});
return null;
}

const moveList = gameData.data.moveList;
const pgnHeaders = gameData.data.pgnHeaders;
const moves = moveList.match(/.{1,2}/g);
if (!moves) {
return "";
Expand Down

0 comments on commit e5b8ad0

Please sign in to comment.