Download src/app/api/chess/challenge/route.ts from NAP1320/RotNot: direct link, hf CLI and curl.
- Browser
- Download file 1.62 kB
-
https://huggingface.co/spaces/NAP1320/RotNot/resolve/main/src/app/api/chess/challenge/route.ts
- Command line
-
hf download hf://spaces/NAP1320/RotNot/src/app/api/chess/challenge/route.ts
-
curl -L -o route.ts https://huggingface.co/spaces/NAP1320/RotNot/resolve/main/src/app/api/chess/challenge/route.ts
1.62 kB
| /** | |
| * POST /api/chess/challenge | |
| * | |
| * Creates a Stockfish bot challenge on Lichess and returns the game URL. | |
| * The user plays the game externally on Lichess, then reports the result | |
| * via POST /api/chess/game-result to earn XP. | |
| * | |
| * Body: | |
| * level number — Stockfish level 1 (easiest) → 8 (strongest). Default: 4. | |
| * userId number — defaults to 1 | |
| */ | |
| import { NextRequest, NextResponse } from "next/server"; | |
| import { challengeStockfish } from "@/lib/lichess"; | |
| import { withApiError, ApiError } from "@/lib/api-error"; | |
| interface ChallengeBody { | |
| level?: number; | |
| userId?: number; | |
| } | |
| /** | |
| * Clamps a Stockfish level to the valid range [1, 8], defaulting to 4. | |
| * Exported for unit testing. | |
| */ | |
| export function clampStockfishLevel(level: unknown): number { | |
| return typeof level === "number" | |
| ? Math.max(1, Math.min(8, Math.round(level))) | |
| : 4; | |
| } | |
| export const POST = withApiError(async (request: NextRequest) => { | |
| let body: ChallengeBody = {}; | |
| try { | |
| body = await request.json(); | |
| } catch { | |
| // body is optional — defaults are fine | |
| } | |
| const level = clampStockfishLevel(body.level); | |
| if (!process.env.LICHESS_API_TOKEN) { | |
| throw new ApiError( | |
| 503, | |
| "LICHESS_API_TOKEN is not configured. Set it in .env to enable Stockfish challenges.", | |
| ); | |
| } | |
| const challenge = await challengeStockfish(level); | |
| if (!challenge) { | |
| throw new ApiError( | |
| 502, | |
| "Failed to create Stockfish challenge on Lichess. Check your API token and try again.", | |
| ); | |
| } | |
| return NextResponse.json({ | |
| gameId: challenge.id, | |
| gameUrl: challenge.url, | |
| level, | |
| }); | |
| }); | |