feat : add chessCom games import
This commit is contained in:
@@ -21,7 +21,7 @@ export const formatGameToDatabase = (game: Chess): Omit<Game, "id"> => {
|
||||
event: headers.Event,
|
||||
site: headers.Site,
|
||||
date: headers.Date,
|
||||
round: headers.Round,
|
||||
round: headers.Round ?? "?",
|
||||
white: {
|
||||
name: headers.White,
|
||||
rating: headers.WhiteElo ? Number(headers.WhiteElo) : undefined,
|
||||
|
||||
41
src/lib/chessCom.ts
Normal file
41
src/lib/chessCom.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import { ChessComGame } from "@/types/chessCom";
|
||||
import { getPaddedMonth } from "./helpers";
|
||||
|
||||
export const getUserRecentGames = async (
|
||||
username: string
|
||||
): Promise<ChessComGame[]> => {
|
||||
const date = new Date();
|
||||
const year = date.getUTCFullYear();
|
||||
const month = date.getUTCMonth() + 1;
|
||||
const paddedMonth = getPaddedMonth(month);
|
||||
|
||||
const res = await fetch(
|
||||
`https://api.chess.com/pub/player/${username}/games/${year}/${paddedMonth}`
|
||||
);
|
||||
|
||||
if (res.status === 404) return [];
|
||||
|
||||
const data = await res.json();
|
||||
|
||||
const games: ChessComGame[] = data?.games ?? [];
|
||||
|
||||
if (games.length < 20) {
|
||||
const previousMonth = month === 1 ? 12 : month - 1;
|
||||
const previousPaddedMonth = getPaddedMonth(previousMonth);
|
||||
const yearToFetch = previousMonth === 12 ? year - 1 : year;
|
||||
|
||||
const resPreviousMonth = await fetch(
|
||||
`https://api.chess.com/pub/player/${username}/games/${yearToFetch}/${previousPaddedMonth}`
|
||||
);
|
||||
|
||||
const dataPreviousMonth = await resPreviousMonth.json();
|
||||
|
||||
games.push(...(dataPreviousMonth?.games ?? []));
|
||||
}
|
||||
|
||||
games.sort((a, b) => {
|
||||
return b.end_time - a.end_time;
|
||||
});
|
||||
|
||||
return games;
|
||||
};
|
||||
7
src/lib/helpers.ts
Normal file
7
src/lib/helpers.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
export const getPaddedMonth = (month: number) => {
|
||||
return month < 10 ? `0${month}` : month;
|
||||
};
|
||||
|
||||
export const capitalize = (s: string) => {
|
||||
return s.charAt(0).toUpperCase() + s.slice(1);
|
||||
};
|
||||
Reference in New Issue
Block a user