Files
music_quiz/apps/server/src/game/saved.ts

58 lines
2.9 KiB
TypeScript

/** 퀴즈 저장·불러오기 (docs/12 Q8): Discord accounts only, 20 per account, deleted only by the owner. */
import type { Database } from 'bun:sqlite';
import { applyConfigPatch, DEFAULT_ROOM_CONFIG, type RoomConfig } from '@mq/shared';
import type { Quiz, Score } from './engine';
export const SAVE_LIMIT = 20;
export interface SavedQuizRow {
id: number;
name: string;
questions: number;
players: number;
updatedAt: number;
}
export class SavedQuizzes {
constructor(private db: Database) {}
list(userId: string): SavedQuizRow[] {
return this.db
.query<{ id: number; name: string; questions: number; scores_json: string; updated_at: number }, [string]>(
'SELECT id, name, questions, scores_json, updated_at FROM saved_quizzes WHERE user_id = ? ORDER BY updated_at DESC',
)
.all(userId)
.map((r) => ({ id: r.id, name: r.name, questions: r.questions, players: (JSON.parse(r.scores_json) as unknown[]).length, updatedAt: r.updated_at }));
}
save(userId: string, name: string, config: RoomConfig, quiz: Quiz, now = Date.now()): number | string {
const n = this.db.query<{ n: number }, [string]>('SELECT COUNT(*) n FROM saved_quizzes WHERE user_id = ?').get(userId)!.n;
if (n >= SAVE_LIMIT) return `퀴즈는 ${SAVE_LIMIT}개까지 저장할 수 있어요. 안 쓰는 퀴즈를 지워 주세요.`;
const scores = [...quiz.scores].map(([id, s]) => ({ id, ...s }));
const r = this.db
.query<{ id: number }, [string, string, string, string, string, number, number, number]>(
'INSERT INTO saved_quizzes (user_id, name, config_json, played_json, scores_json, questions, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) RETURNING id',
)
.get(userId, name, JSON.stringify(config), JSON.stringify(quiz.played), JSON.stringify(scores), quiz.played.length, now, now)!;
return r.id;
}
load(userId: string, id: number): { name: string; config: RoomConfig; quiz: Quiz } | null {
const r = this.db
.query<{ name: string; config_json: string; played_json: string; scores_json: string }, [number, string]>(
'SELECT name, config_json, played_json, scores_json FROM saved_quizzes WHERE id = ? AND user_id = ?',
)
.get(id, userId);
if (!r) return null;
// Settings saved by an older version: whatever no longer validates falls back to the default.
const merged = applyConfigPatch(DEFAULT_ROOM_CONFIG, JSON.parse(r.config_json));
const config = typeof merged === 'string' ? DEFAULT_ROOM_CONFIG : merged;
const scores = new Map<string, Score>((JSON.parse(r.scores_json) as ({ id: string } & Score)[]).map(({ id: uid, ...s }) => [uid, s]));
return { name: r.name, config, quiz: { played: JSON.parse(r.played_json) as number[], scores } };
}
remove(userId: string, id: number): boolean {
return this.db.query('DELETE FROM saved_quizzes WHERE id = ? AND user_id = ?').run(id, userId).changes > 0;
}
}