refacto : load game

This commit is contained in:
GuillaumeSD
2025-06-10 02:42:43 +02:00
parent 839f87a2e8
commit 5e2d944513
15 changed files with 310 additions and 556 deletions

View File

@@ -3,11 +3,12 @@ import { sortLines } from "./engine/helpers/parseResults";
import {
LichessError,
LichessEvalBody,
LichessRawGameData,
LichessGame,
LichessResponse,
} from "@/types/lichess";
import { logErrorToSentry } from "./sentry";
import { formatUciPv } from "./chess";
import { LoadedGame } from "@/types/game";
export const getLichessEval = async (
fen: string,
@@ -58,7 +59,7 @@ export const getLichessEval = async (
export const getLichessUserRecentGames = async (
username: string,
signal?: AbortSignal
): Promise<LichessRawGameData[]> => {
): Promise<LoadedGame[]> => {
const res = await fetch(
`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" }, signal }
@@ -69,12 +70,12 @@ export const getLichessUserRecentGames = async (
}
const rawData = await res.text();
const games: LichessRawGameData[] = rawData
const games: LichessGame[] = rawData
.split("\n")
.filter((game) => game.length > 0)
.map((game) => JSON.parse(game));
return games;
return games.map(formatLichessGame);
};
const fetchLichessEval = async (
@@ -94,3 +95,33 @@ const fetchLichessEval = async (
return { error: LichessError.NotFound };
}
};
const formatLichessGame = (data: LichessGame): LoadedGame => {
return {
id: data.id,
pgn: data.pgn || "",
white: {
name: data.players.white.user?.name || "White",
rating: data.players.white.rating,
title: data.players.white.user?.title,
},
black: {
name: data.players.black.user?.name || "Black",
rating: data.players.black.rating,
title: data.players.black.user?.title,
},
result: getGameResult(data),
timeControl: `${Math.floor(data.clock?.initial / 60 || 0)}+${data.clock?.increment || 0}`,
date: new Date(data.createdAt || data.lastMoveAt).toLocaleDateString(),
movesNb: data.moves?.split(" ").length || 0,
url: `https://lichess.org/${data.id}`,
};
};
const getGameResult = (data: LichessGame): string => {
if (data.status === "draw") return "1/2-1/2";
if (data.winner) return data.winner === "white" ? "1-0" : "0-1";
return "*";
};