Files
nuitdelinfo2023/api/Classes/Games.js
2023-12-07 22:27:05 +01:00

75 lines
1.4 KiB
JavaScript

import { pool } from '../modules/database.js';
class Game {
constructor(id = null, playerId) {
this.id = id;
this.player = playerId;
this.questions = [];
}
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;
}
}
}
class Answer {
constructor(id = null, answer = null, correct = null) {
this.id = id;
this.answer = answer;
this.correct = correct;
}
}
export { Game };