Files
nuitdelinfo2023/api/Classes/Games.js
2023-12-07 23:26:41 +01:00

110 lines
2.2 KiB
JavaScript

import { pool } from '../modules/database.js';
class Game {
constructor(id = null, playerId) {
this.id = id;
this.player = playerId;
this.questions = [];
}
async get() {
try {
const [rows] = await pool.execute(
'SELECT * FROM games WHERE id = ? AND player = ? LIMIT 1', [this.id, this.player],
);
if (!rows.length) return false;
const [questions] = await pool.execute(
'SELECT * FROM games_questions WHERE game = ?', [this.id],
);
questions.forEach(q => {
const question = new Question(q.id, q.question);
this.questions.push(question);
});
return true;
}
catch (error) {
console.error(error);
return false;
}
}
async create() {
try {
const [rows] = await pool.execute(
'INSERT INTO games (player) VALUES (?)', [this.player],
);
this.id = rows.insertId;
return true;
}
catch (error) {
console.error(error);
return false;
}
}
async generateQuestions(themeId) {
try {
const [rows] = await pool.execute(
'SELECT * FROM questions ORDER BY RAND() LIMIT 10 WHERE theme = ?', [themeId],
);
rows.forEach(row => {
const question = new Question(row.id, row.question);
this.questions.push(question);
});
return true;
}
catch (error) {
console.error(error);
return false;
}
}
}
class Question {
constructor(id = null, question = null) {
this.id = id;
this.question = question;
this.answers = [];
}
async fetchAnswers() {
try {
const [rows] = await pool.execute(
'SELECT * FROM answers WHERE question = ?', [this.id],
);
rows.forEach(row => {
const answer = new Answer(row.id, row.answer, row.correct);
this.answers.push(answer);
});
return true;
}
catch (error) {
console.error(error);
return false;
}
}
async verifyAnswer(answerId) {
try {
const [rows] = await pool.execute(
'SELECT * FROM answers WHERE question = ? AND id = ? AND correct = 1', [this.id, answerId],
);
if (!rows.length) return false;
return true;
}
catch (error) {
console.error(error);
return false;
}
}
}
class Answer {
constructor(id = null, answer = null, correct = null) {
this.id = id;
this.answer = answer;
this.correct = correct;
}
}
export { Game };