fix : loading game from CC and lichess

This commit is contained in:
GuillaumeSD
2025-05-12 14:11:24 +02:00
parent 046d53e7dc
commit 2b79434d45
4 changed files with 44 additions and 25 deletions

View File

@@ -2,7 +2,8 @@ import { ChessComGame } from "@/types/chessCom";
import { getPaddedNumber } from "./helpers"; import { getPaddedNumber } from "./helpers";
export const getChessComUserRecentGames = async ( export const getChessComUserRecentGames = async (
username: string username: string,
signal?: AbortSignal
): Promise<ChessComGame[]> => { ): Promise<ChessComGame[]> => {
const date = new Date(); const date = new Date();
const year = date.getUTCFullYear(); const year = date.getUTCFullYear();
@@ -10,10 +11,13 @@ export const getChessComUserRecentGames = async (
const paddedMonth = getPaddedNumber(month); const paddedMonth = getPaddedNumber(month);
const res = await fetch( const res = await fetch(
`https://api.chess.com/pub/player/${username}/games/${year}/${paddedMonth}` `https://api.chess.com/pub/player/${username}/games/${year}/${paddedMonth}`,
{ method: "GET", signal }
); );
if (res.status === 404) return []; if (res.status >= 400) {
throw new Error("Error fetching games from Chess.com");
}
const data = await res.json(); const data = await res.json();

View File

@@ -56,14 +56,17 @@ export const getLichessEval = async (
}; };
export const getLichessUserRecentGames = async ( export const getLichessUserRecentGames = async (
username: string username: string,
signal?: AbortSignal
): Promise<LichessGame[]> => { ): Promise<LichessGame[]> => {
const res = await fetch( const res = await fetch(
`https://lichess.org/api/games/user/${username}?until=${Date.now()}&max=50&pgnInJson=true&sort=dateDesc&clocks=true`, `https://lichess.org/api/games/user/${username}?until=${Date.now()}&max=50&pgnInJson=true&sort=dateDesc&clocks=true`,
{ method: "GET", headers: { accept: "application/x-ndjson" } } { method: "GET", headers: { accept: "application/x-ndjson" }, signal }
); );
if (res.status === 404) return []; if (res.status >= 400) {
throw new Error("Error fetching games from Lichess");
}
const rawData = await res.text(); const rawData = await res.text();
const games: LichessGame[] = rawData const games: LichessGame[] = rawData

View File

@@ -23,7 +23,7 @@ export default function ChessComInput({ onSelect }: Props) {
"chesscom-username", "chesscom-username",
"" ""
); );
const debouncedUsername = useDebounce(chessComUsername, 200); const debouncedUsername = useDebounce(chessComUsername, 300);
const setBoardOrientation = useSetAtom(boardOrientationAtom); const setBoardOrientation = useSetAtom(boardOrientationAtom);
const { const {
@@ -33,7 +33,9 @@ export default function ChessComInput({ onSelect }: Props) {
} = useQuery({ } = useQuery({
queryKey: ["CCUserGames", debouncedUsername], queryKey: ["CCUserGames", debouncedUsername],
enabled: !!debouncedUsername, enabled: !!debouncedUsername,
queryFn: () => getChessComUserRecentGames(debouncedUsername ?? ""), queryFn: ({ signal }) =>
getChessComUserRecentGames(debouncedUsername ?? "", signal),
retry: 1,
}); });
return ( return (
@@ -72,7 +74,7 @@ export default function ChessComInput({ onSelect }: Props) {
onClick={() => { onClick={() => {
setBoardOrientation( setBoardOrientation(
chessComUsername.toLowerCase() !== chessComUsername.toLowerCase() !==
game.black.username.toLowerCase() game.black?.username?.toLowerCase()
); );
onSelect(game.pgn); onSelect(game.pgn);
}} }}
@@ -80,16 +82,20 @@ export default function ChessComInput({ onSelect }: Props) {
key={game.uuid} key={game.uuid}
> >
<ListItemText <ListItemText
primary={`${capitalize(game.white.username) || "White"} (${ primary={`${capitalize(game.white?.username || "white")} (${
game.white.rating || "?" game.white?.rating || "?"
}) vs ${capitalize(game.black.username) || "Black"} (${ }) vs ${capitalize(game.black?.username || "black")} (${
game.black.rating || "?" game.black?.rating || "?"
})`} })`}
secondary={`${capitalize(game.time_class)} played at ${new Date( secondary={
game.end_time * 1000 game.end_time
) ? `${capitalize(game.time_class || "game")} played at ${new Date(
.toLocaleString() game.end_time * 1000
.slice(0, -3)}`} )
.toLocaleString()
.slice(0, -3)}`
: undefined
}
slotProps={{ slotProps={{
primary: { noWrap: true }, primary: { noWrap: true },
secondary: { noWrap: true }, secondary: { noWrap: true },

View File

@@ -23,7 +23,7 @@ export default function LichessInput({ onSelect }: Props) {
"lichess-username", "lichess-username",
"" ""
); );
const debouncedUsername = useDebounce(lichessUsername, 200); const debouncedUsername = useDebounce(lichessUsername, 500);
const setBoardOrientation = useSetAtom(boardOrientationAtom); const setBoardOrientation = useSetAtom(boardOrientationAtom);
const { const {
@@ -33,7 +33,9 @@ export default function LichessInput({ onSelect }: Props) {
} = useQuery({ } = useQuery({
queryKey: ["LichessUserGames", debouncedUsername], queryKey: ["LichessUserGames", debouncedUsername],
enabled: !!debouncedUsername, enabled: !!debouncedUsername,
queryFn: () => getLichessUserRecentGames(debouncedUsername ?? ""), queryFn: ({ signal }) =>
getLichessUserRecentGames(debouncedUsername ?? "", signal),
retry: 1,
}); });
return ( return (
@@ -72,7 +74,7 @@ export default function LichessInput({ onSelect }: Props) {
onClick={() => { onClick={() => {
setBoardOrientation( setBoardOrientation(
lichessUsername.toLowerCase() !== lichessUsername.toLowerCase() !==
game.players?.black?.user?.name.toLowerCase() game.players?.black?.user?.name?.toLowerCase()
); );
onSelect(game.pgn); onSelect(game.pgn);
}} }}
@@ -87,11 +89,15 @@ export default function LichessInput({ onSelect }: Props) {
capitalize(game.players?.black?.user?.name || "black") || capitalize(game.players?.black?.user?.name || "black") ||
"Black" "Black"
} (${game.players?.black?.rating || "?"})`} } (${game.players?.black?.rating || "?"})`}
secondary={`${capitalize(game.speed)} played at ${new Date( secondary={
game.lastMoveAt game.lastMoveAt
) ? `${capitalize(game.speed || "game")} played at ${new Date(
.toLocaleString() game.lastMoveAt
.slice(0, -3)}`} )
.toLocaleString()
.slice(0, -3)}`
: undefined
}
slotProps={{ slotProps={{
primary: { noWrap: true }, primary: { noWrap: true },
secondary: { noWrap: true }, secondary: { noWrap: true },