From 40035bd9cea21c4173f6727ba54d94f4fde44a9c Mon Sep 17 00:00:00 2001 From: LarsVomMars Date: Tue, 26 Jan 2021 11:57:48 +0100 Subject: Questions update --- questions/index.js | 19 +++++++++++++------ questions/public/index.html | 5 +---- questions/public/script.js | 46 ++++++++++++++++++++++++++------------------- 3 files changed, 41 insertions(+), 29 deletions(-) (limited to 'questions') diff --git a/questions/index.js b/questions/index.js index 1f0f4ce..96bbb8b 100644 --- a/questions/index.js +++ b/questions/index.js @@ -7,15 +7,16 @@ app.use("/", checkUser, express.static(__dirname + "/public")); app.get("/api/question/:id", checkUser, async (req, res) => { try { - const questions = await db.query("SELECT id, question FROM question_questions"); + const questions = await db.query("SELECT id, question FROM question_questions ORDER BY id"); const id = +req.params.id; if (id >= 0 && id < questions.length) { const question = questions[id]; const answers = await db.query( - "SELECT answer FROM question_answers WHERE question_id = ? AND user_id = ?", + "SELECT option_id FROM question_answers WHERE question_id = ? AND user_id = ?", [question.id, req.session.uid], ); - question.answer = answers.length > 0 ? answers[0].answer : undefined; + question.answer = answers.length > 0 ? answers[0].option_id : undefined; + question.options = await db.query("SELECT id, answer_option FROM question_options WHERE question_id = ?", [question.id]); res.json(question); } else { res.json({}); @@ -45,21 +46,27 @@ app.get("/api/questions", checkUser, async (req, res) => { }); app.post("/api/answer", checkUser, async (req, res) => { - return await answer(req, res, "INSERT INTO question_answers (answer, question_id, user_id) VALUE (?,?,?)"); + return await answer(req, res, "INSERT INTO question_answers (option_id, question_id, user_id) VALUE (?,?,?)"); }); app.put("/api/answer", checkUser, async (req, res) => { - return await answer(req, res, "UPDATE question_answers SET answer = ? WHERE question_id = ? AND user_id = ?"); + return await answer(req, res, "UPDATE question_answers SET option_id = ? WHERE question_id = ? AND user_id = ?"); }); async function answer(req, res, qu) { const { question, answer } = req.body; + const fail = { success: false }; try { + const possibleAnswers = await db.query(`SELECT qo.id + FROM question_questions qq + INNER JOIN question_options qo on qq.id = qo.question_id + WHERE qq.id = ?`, [question]); + if (possibleAnswers.find(value => +value.id === +answer) === undefined) return res.json(fail); // Answer not for question await db.query(qu, [answer, question, req.session.uid]); res.json({ success: true }); } catch (e) { console.error(e); - res.json({ success: false }); + res.json(fail); } } diff --git a/questions/public/index.html b/questions/public/index.html index 90244f5..e21db81 100644 --- a/questions/public/index.html +++ b/questions/public/index.html @@ -26,10 +26,7 @@
- +