Download src/app/api/chess/puzzle/route.ts from NAP1320/RotNot: direct link, hf CLI and curl.
- Browser
- Download file 2.02 kB
-
https://huggingface.co/spaces/NAP1320/RotNot/resolve/main/src/app/api/chess/puzzle/route.ts
- Command line
-
hf download hf://spaces/NAP1320/RotNot/src/app/api/chess/puzzle/route.ts
-
curl -L -o route.ts https://huggingface.co/spaces/NAP1320/RotNot/resolve/main/src/app/api/chess/puzzle/route.ts
2.02 kB
| /** | |
| * GET /api/chess/puzzle | |
| * | |
| * Fetches a Lichess puzzle and returns it formatted for react-chessboard. | |
| * Query params: | |
| * ?daily=true — fetch today's daily puzzle instead of a random one | |
| */ | |
| import { NextRequest, NextResponse } from "next/server"; | |
| import { | |
| getLichessPuzzle, | |
| getLichessDailyPuzzle, | |
| type LichessPuzzleResponse, | |
| } from "@/lib/lichess"; | |
| import { withApiError } from "@/lib/api-error"; | |
| import { fenFromPgn } from "@/lib/chess/pgn"; | |
| export interface ChessPuzzlePayload { | |
| id: string; | |
| /** Starting FEN for the puzzle position (computed server-side from the game PGN). */ | |
| fen: string; | |
| /** Full game PGN from Lichess (retained for client-side chess.js move validation). */ | |
| pgn: string; | |
| /** UCI solution moves starting from the puzzle position. The first move is the opponent's forcing move. */ | |
| solution: string[]; | |
| rating: number; | |
| themes: string[]; | |
| plays: number; | |
| gameUrl: string; | |
| } | |
| /** | |
| * Formats a raw Lichess puzzle response into a ChessPuzzlePayload. | |
| * | |
| * The FEN is computed server-side by replaying the full game PGN with chess.js, | |
| * yielding the exact board position where the puzzle begins. | |
| */ | |
| function formatPuzzle(raw: LichessPuzzleResponse): ChessPuzzlePayload { | |
| const pgn = raw.game.pgn; | |
| const fen = fenFromPgn(pgn) ?? ""; | |
| return { | |
| id: raw.puzzle.id, | |
| fen, | |
| pgn, | |
| solution: raw.puzzle.solution, | |
| rating: raw.puzzle.rating, | |
| themes: raw.puzzle.themes, | |
| plays: raw.puzzle.plays, | |
| gameUrl: `https://lichess.org/${raw.game.id}`, | |
| }; | |
| } | |
| export const GET = withApiError(async (request: NextRequest) => { | |
| const { searchParams } = new URL(request.url); | |
| const isDaily = searchParams.get("daily") === "true"; | |
| const raw = isDaily | |
| ? await getLichessDailyPuzzle() | |
| : await getLichessPuzzle(); | |
| if (!raw) { | |
| return NextResponse.json( | |
| { error: "Failed to fetch puzzle from Lichess. Check LICHESS_API_TOKEN.", status: 502 }, | |
| { status: 502 }, | |
| ); | |
| } | |
| return NextResponse.json(formatPuzzle(raw)); | |
| }); | |