Files
nuitdelinfo2023/api/routes/games.js
2023-12-08 03:53:09 +01:00

44 lines
1.7 KiB
JavaScript

import express from 'express';
import { pool } from '../modules/database.js';
import { verifyToken } from '../modules/token.js';
import { respondWithStatus, respondWithStatusJSON } from '../modules/requestHandler.js';
import { Game, Question } from '../Classes/Games.js';
const router = express.Router();
router.post('/create/:theme', verifyToken, async (req, res) => {
const game = new Game(null, req.userId);
await game.create();
await game.generateQuestions(req.params.theme);
return await respondWithStatusJSON(res, 200, {
message: 'Successfully created game',
game,
});
});
router.post('/verify/:game', verifyToken, async (req, res) => {
const [rows] = await pool.execute(
'SELECT * FROM games WHERE id = ? AND player = ? LIMIT 1', [req.params.game, req.userId],
);
if (!rows.length) return await respondWithStatus(res, 404, 'Game not found');
const { question, answer } = req.body;
if (![question, answer].every(Boolean)) return await respondWithStatus(res, 400, 'Missing fields');
const q = new Question(question);
const [gameQuestions] = await pool.execute('SELECT * FROM game_questions WHERE game = ? AND question = ?', [req.params.game, question]);
if (!gameQuestions.length) return await respondWithStatus(res, 404, 'Question not found');
if (gameQuestions[0].score) return await respondWithStatus(res, 400, 'Question already answered');
if (q.verifyAnswer(answer)) {
await pool.execute('UPDATE game_questions SET score = 1 WHERE game = ? AND question = ?', [req.params.game, question]);
res.status(200).json({
message: 'Answer is correct',
});
}
else {
res.status(200).json({
message: 'Answer is incorrect',
});
}
});
export default router;