nerdware/apps/server/src/game/modes/quiz/pool.ts
AyoubBenziza 9fe30feec5 feat(server): Drizzle + PostgreSQL schema + Open Trivia DB seed
- Drizzle (postgres-js) setup: schema (quiz_category, quiz_question,
  quiz_played, game_history), client (nullable — no DATABASE_URL → null),
  drizzle.config, initial migration, migrate script
- Open Trivia DB seed: curated geek categories, mcq + truefalse, base64
  decode (incl. type/difficulty), 1 req/5s rate limit, idempotent
  (prompt unique); also seeds the FR in-code bank as source 'manual'
- quiz wired to the DB: per-room pool preloaded at game start (loadQuizPool
  excludes already-played), records quiz_played for cross-session
  anti-repeat; falls back to the in-code bank when no DB
- docker-compose for local Postgres; db:* scripts; DATABASE_URL in env

Roadmap V1 step 5. Verified against a real Postgres: migrate + seed (270
OpenTDB + 10 manual), DB-backed game serves OpenTDB questions and fills
quiz_played; no-DB fallback still serves the in-code bank.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-10 12:24:17 +02:00

61 lines
1.8 KiB
TypeScript

// File d'attente de questions par room. Préchargée au lancement de la partie
// depuis la DB (si dispo), sinon depuis la banque en dur. Le QuizRound y pioche.
import { hasDb } from "../../../db"
import { loadQuizPool } from "../../../db/quiz-repo"
import type { ServerRoom } from "../../../rooms"
import { QUIZ_QUESTIONS, type QuizQuestion } from "./questions"
interface RoomPool {
queue: QuizQuestion[]
/** true si les questions viennent de la DB (→ marquer jouées). */
fromDb: boolean
}
const poolByRoom = new WeakMap<ServerRoom, RoomPool>()
function shuffle<T>(items: T[]): T[] {
const arr = [...items]
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1))
;[arr[i], arr[j]] = [arr[j], arr[i]]
}
return arr
}
/** Précharge les questions de la partie. À appeler avant de lancer le moteur. */
export async function prepareQuizForRoom(room: ServerRoom): Promise<void> {
const needed = room.settings.rounds.filter((r) => r.type === "quiz").length
let queue: QuizQuestion[] = []
let fromDb = false
if (hasDb) {
try {
queue = await loadQuizPool(room.code, Math.max(needed, 1))
fromDb = queue.length > 0
} catch (err) {
console.error("[quiz] chargement DB échoué, fallback banque en dur", err)
}
}
if (queue.length === 0) {
queue = shuffle(QUIZ_QUESTIONS)
fromDb = false
}
poolByRoom.set(room, { queue, fromDb })
}
/** Pioche la prochaine question. Fallback aléatoire si la file est vide. */
export function takeQuestion(room: ServerRoom): {
question: QuizQuestion
fromDb: boolean
} {
const pool = poolByRoom.get(room)
if (pool && pool.queue.length > 0) {
return { question: pool.queue.shift()!, fromDb: pool.fromDb }
}
const question =
QUIZ_QUESTIONS[Math.floor(Math.random() * QUIZ_QUESTIONS.length)]
return { question, fromDb: false }
}