feat: complete day 8

This commit is contained in:
Ayobami
2025-07-15 17:41:52 +01:00
parent 10447cd05e
commit 7d8ed6d0ee
7 changed files with 407 additions and 293 deletions
+48 -34
View File
@@ -1,4 +1,4 @@
'use strict'; "use strict";
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2020*/ /*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2020*/
/** /**
* Sequelize File * Sequelize File
@@ -8,49 +8,63 @@
* @author Ryan Wong * @author Ryan Wong
* *
*/ */
const fs = require('fs'); const fs = require("fs");
const path = require('path'); const path = require("path");
let Sequelize = require('sequelize'); let Sequelize = require("sequelize");
const basename = path.basename(__filename); const basename = path.basename(__filename);
const { DataTypes } = require('sequelize'); const { DataTypes } = require("sequelize");
const config = { const config = {
DB_DATABASE: 'mysql', DB_DATABASE: "mysql",
DB_USERNAME: 'root', DB_USERNAME: "root",
DB_PASSWORD: 'root', DB_PASSWORD: process.env.DB_PASSWORD || "root",
DB_ADAPTER: 'mysql', DB_ADAPTER: "mysql",
DB_NAME: 'day_1', DB_NAME: "day_8",
DB_HOSTNAME: 'localhost', DB_HOSTNAME: "localhost",
DB_PORT: 3306, DB_PORT: 3306,
}; };
let db = {}; let db = {};
let sequelize = new Sequelize(config.DB_DATABASE, config.DB_USERNAME, config.DB_PASSWORD, { let sequelize = new Sequelize(
dialect: config.DB_ADAPTER, config.DB_NAME,
username: config.DB_USERNAME, config.DB_USERNAME,
password: config.DB_PASSWORD, config.DB_PASSWORD,
database: config.DB_NAME, {
host: config.DB_HOSTNAME, dialect: config.DB_ADAPTER,
port: config.DB_PORT, username: config.DB_USERNAME,
logging: console.log, password: config.DB_PASSWORD,
timezone: '-04:00', database: config.DB_NAME,
pool: { host: config.DB_HOSTNAME,
maxConnections: 1, port: config.DB_PORT,
minConnections: 0, logging: console.log,
maxIdleTime: 100, timezone: "-04:00",
}, pool: {
define: { maxConnections: 1,
timestamps: false, minConnections: 0,
underscoredAll: true, maxIdleTime: 100,
underscored: true, },
}, define: {
}); timestamps: false,
underscoredAll: true,
underscored: true,
},
}
);
// sequelize.sync({ force: true }); sequelize
.sync()
.then(() => {
console.log("All tables synced successfully.");
})
.catch((err) => {
console.error("Failed to sync tables:", err);
});
fs.readdirSync(__dirname) fs.readdirSync(__dirname)
.filter((file) => { .filter((file) => {
return file.indexOf('.') !== 0 && file !== basename && file.slice(-3) === '.js'; return (
file.indexOf(".") !== 0 && file !== basename && file.slice(-3) === ".js"
);
}) })
.forEach((file) => { .forEach((file) => {
var model = require(path.join(__dirname, file))(sequelize, DataTypes); var model = require(path.join(__dirname, file))(sequelize, DataTypes);
@@ -66,4 +80,4 @@ Object.keys(db).forEach((modelName) => {
db.sequelize = sequelize; db.sequelize = sequelize;
db.Sequelize = Sequelize; db.Sequelize = Sequelize;
module.exports = db; module.exports = db;
+34
View File
@@ -0,0 +1,34 @@
module.exports = (sequelize, DataTypes) => {
const Question = sequelize.define(
"question",
{
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
quizId: {
type: DataTypes.INTEGER,
allowNull: false,
references: {
model: "quiz",
key: "id",
},
},
questionText: DataTypes.STRING,
options: DataTypes.JSON,
answer: DataTypes.STRING,
},
{
timestamps: true,
freezeTableName: true,
tableName: "question",
}
);
Question.associate = (models) => {
Question.belongsTo(models.quiz, { foreignKey: "quizId", as: "quiz" });
};
return Question;
};
+25
View File
@@ -0,0 +1,25 @@
module.exports = (sequelize, DataTypes) => {
const Quiz = sequelize.define(
"quiz",
{
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
title: DataTypes.STRING,
description: DataTypes.STRING,
},
{
timestamps: true,
freezeTableName: true,
tableName: "quiz",
}
);
Quiz.associate = (models) => {
Quiz.hasMany(models.question, { foreignKey: "quizId", as: "questions" });
};
return Quiz;
};
+2 -1
View File
@@ -3,7 +3,8 @@
"version": "0.0.0", "version": "0.0.0",
"private": true, "private": true,
"scripts": { "scripts": {
"start": "node ./bin/www" "start": "node ./bin/www",
"dev": "node --watch --env-file=.env ./bin/www"
}, },
"dependencies": { "dependencies": {
"cookie-parser": "~1.4.4", "cookie-parser": "~1.4.4",
+227 -255
View File
@@ -1,277 +1,249 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="./style.css"> <link rel="stylesheet" href="./style.css" />
<title>Quiz</title> <title>Quiz</title>
<style> <style>
@import url("https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600;700&display=swap"); @import url("https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600;700&display=swap");
* { * {
box-sizing: border-box; box-sizing: border-box;
margin: 0; margin: 0;
padding: 0; padding: 0;
} }
html, html,
body { body {
font-family: "Open Sans", sans-serif; font-family: "Open Sans", sans-serif;
line-height: 1.4; line-height: 1.4;
background-color: #333; background-color: #333;
} }
.main { .main {
margin: 0 auto; margin: 0 auto;
width: 600px; width: 600px;
margin-top: 200px; margin-top: 200px;
background-color: white; background-color: white;
padding: 20px; padding: 20px;
border-radius: 10px; border-radius: 10px;
/* box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px; */ /* box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px; */
box-shadow: rgba(0, 0, 0, 0.05) 0px 6px 24px 0px, box-shadow: rgba(0, 0, 0, 0.05) 0px 6px 24px 0px,
rgba(0, 0, 0, 0.08) 0px 0px 0px 1px; rgba(0, 0, 0, 0.08) 0px 0px 0px 1px;
} }
.hidden { .hidden {
display: none; display: none;
} }
button { button {
padding: 10px; padding: 10px;
border: 10px; border: 10px;
background-color: teal; background-color: teal;
font-weight: bold; font-weight: bold;
color: white; color: white;
border-radius: 2px; border-radius: 2px;
} }
button:hover { button:hover {
cursor: pointer; cursor: pointer;
} }
input { input {
margin: 10px; margin: 10px;
border: none; border: none;
font-size: large; font-size: large;
color: rgba(0, 128, 128, 0.616); color: rgba(0, 128, 128, 0.616);
} }
textarea { textarea {
border: none; border: none;
font-size: large; font-size: large;
color: rgba(0, 128, 128, 0.616); color: rgba(0, 128, 128, 0.616);
} }
ul { ul {
list-style: none; list-style: none;
margin-bottom: 10px; margin-bottom: 10px;
} }
#bool { #bool {
list-style: none; list-style: none;
display: flex; display: flex;
flex-direction: row; flex-direction: row;
margin: 10px; margin: 10px;
} }
textarea:focus, textarea:focus,
input:focus { input:focus {
outline: none; outline: none;
} }
#yourAnswers p {
margin-top: 30px;
color: teal;
}
#yourAnswers p {
margin-top: 30px;
color: teal;
}
</style> </style>
</head> </head>
<body> <body>
<div class="main">
<div class="main"> <h1>Quiz</h1>
<div id="yourAnswers" class="hidden">
<h1>Your answers</h1>
<h1>Quiz</h1> <pre id="answerObject"></pre>
<div id="yourAnswers" class="hidden"> </div>
<h1 >Your answers</h1> <div class="question" id="questionsDiv">
<pre id="answerObject"></pre> <h2 id="title"></h2>
</div> <ul id="selectionList"></ul>
<div class="question" id="questionsDiv"> <input id="short" type="text" class="hidden" />
<textarea
<h2 id="title"></h2> name=""
<ul id ='selectionList'> </ul> id="long"
<input id="short" type="text" class="hidden"/> class="hidden"
<textarea name="" id="long" class="hidden" cols="30" rows="10"></textarea> cols="30"
<div id="bool"></div> rows="10"
<button id="next">Next</button> ></textarea>
</div> <div id="bool"></div>
</div> <button id="next">Next</button>
</div>
</div>
<script> <script>
let quiz = [ // Fetch quiz data from API
{ fetch("/api/quiz")
id: 1, .then((res) => res.json())
type: "short_answer", .then((result) => {
question: "Why is the sky blue?", if (result.success) {
answers: [], // Transform API data to match expected quiz array structure
correct_answer: 0, const apiQuiz = result.data;
}, window.quiz = apiQuiz.questions.map((q, idx) => ({
{ id: q.id,
id: 2, type: "multiple_choice", // You can enhance this to support more types if needed
type: "multiple_choice", question: q.questionText,
question: "Why is the sky blue?", answers: q.options.map((opt, i) => ({ id: i + 1, answer: opt })),
answers: [ correct_answer: q.answer,
{ id: 1, answer: "Because of physics" }, }));
{ id: 2, answer: "Because that the way it always was" }, // Start quiz
{ id: 3, answer: "I don't know" }, window.i = 0;
], window.answers = {};
correct_answer: 1, populateQuestion(window.i);
}, } else {
{ alert("Failed to load quiz: " + result.error);
id: 3, }
type: "multiple_selection_choice", })
question: "Why is the sky blue?", .catch((err) => {
answers: [ alert("Error fetching quiz: " + err);
{ id: 1, answer: "Because of physics" }, });
{ id: 2, answer: "Because that the way it always was" },
{ id: 3, answer: "I don't know" },
],
correct_answer: 1,
},
{
id: 4,
type: "long_text",
question: "Why is the sky blue?",
answers: [],
correct_answer: 0,
},
{
id: 5,
type: "description",
question: "random text to show to the user",
answers: [],
correct_answer: 0,
},
{
id: 6,
type: "true_false",
question: "Is the sky blue",
answers: [],
correct_answer: 2,
},
];
let nextButton = document.getElementById("next"); let nextButton = document.getElementById("next");
let title = document.getElementById("title"); let title = document.getElementById("title");
let selectionList = document.getElementById("selectionList"); let selectionList = document.getElementById("selectionList");
let bool = document.getElementById("bool"); let bool = document.getElementById("bool");
let inp = document.getElementById("short"); let inp = document.getElementById("short");
let text = document.getElementById("long"); let text = document.getElementById("long");
let yourAnswers = document.getElementById("yourAnswers"); let yourAnswers = document.getElementById("yourAnswers");
let questionsDiv = document.getElementById("questionsDiv"); let questionsDiv = document.getElementById("questionsDiv");
let i = 0;
let answers = {}; //step
nextButton.onclick = function () {
//get the answers
if (quiz[i].type == "short_answer") {
let x = document.getElementsByClassName("current")[0];
let currentAnswer = x.value;
let question = quiz[i].question;
let answer = { [question]: currentAnswer };
answers = { ...answers, [quiz[i].id]: { ...answer } };
x.classList.toggle("hidden");
x.classList.remove("current");
} else if (
quiz[i].type == "multiple_choice" ||
quiz[i].type == "multiple_selection_choice"
) {
let x = document.querySelector(`input[name="question${i}_choice"]`);
let currentAnswer = x.value;
let question = quiz[i].question;
let answer = { [question]: currentAnswer };
answers = { ...answers, [quiz[i].id]: { ...answer } };
x.classList.toggle("hidden");
} else if (
quiz[i].type == "long_text" ||
quiz[i].type == "description"
) {
let x = document.getElementsByClassName("current")[0];
let currentAnswer = x.value;
let question = quiz[i].question;
let answer = { [question]: currentAnswer };
answers = { ...answers, [quiz[i].id]: { ...answer } };
x.classList.toggle("hidden");
x.classList.remove("current");
} else if (quiz[i].type == "true_false") {
let x = document.querySelector("input[name=bool]");
let currentAnswer = x.value;
let question = quiz[i].question;
let answer = { [question]: currentAnswer };
answers = { ...answers, [quiz[i].id]: { ...answer } };
x.classList.toggle("hidden");
}
console.log(i);
++i;
if (i > quiz.length - 1) {
//display answer
questionsDiv.classList.toggle("hidden");
yourAnswers.classList.toggle("hidden");
const myJSON = JSON.stringify(answers, null, "\t");
document.getElementById("answerObject").innerHTML = myJSON;
return;
}
populateQuestion(i);
};
//step //generate question
nextButton.onclick = function () { function populateQuestion(qNum) {
//get the answers let individualQuestion = quiz[qNum];
if (quiz[i].type == "short_answer") { title.innerText = individualQuestion.question;
let x = document.getElementsByClassName("current")[0];
let currentAnswer = x.value;
let question = quiz[i].question;
let answer = { [question]: currentAnswer };
answers = { ...answers, [quiz[i].id]: { ...answer } };
x.classList.toggle("hidden");
x.classList.remove("current");
} else if (
quiz[i].type == "multiple_choice" ||
quiz[i].type == "multiple_selection_choice"
) {
let x = document.querySelector(`input[name="question${i}_choice"]`);
let currentAnswer = x.value;
let question = quiz[i].question;
let answer = { [question]: currentAnswer };
answers = { ...answers, [quiz[i].id]: { ...answer } };
x.classList.toggle("hidden");
} else if (quiz[i].type == "long_text" || quiz[i].type == "description") {
let x = document.getElementsByClassName("current")[0];
let currentAnswer = x.value;
let question = quiz[i].question;
let answer = { [question]: currentAnswer };
answers = { ...answers, [quiz[i].id]: { ...answer } };
x.classList.toggle("hidden");
x.classList.remove("current");
} else if (quiz[i].type == "true_false") {
let x = document.querySelector("input[name=bool]");
let currentAnswer = x.value;
let question = quiz[i].question;
let answer = { [question]: currentAnswer };
answers = { ...answers, [quiz[i].id]: { ...answer } };
x.classList.toggle("hidden");
}
console.log(i);
++i;
if (i > quiz.length - 1) {
//display answer
questionsDiv.classList.toggle("hidden");
yourAnswers.classList.toggle("hidden");
const myJSON = JSON.stringify(answers, null, "\t");
document.getElementById("answerObject").innerHTML = myJSON;
return;
}
populateQuestion(i);
};
//generate question //condition to check type of question
function populateQuestion(qNum) {
let individualQuestion = quiz[qNum];
title.innerText = individualQuestion.question;
//condition to check type of question if (individualQuestion.type == "short_answer") {
selectionList.innerHTML = "";
short.classList.toggle("hidden");
short.classList.add("current");
short.placeholder = "your reason here";
} else if (
individualQuestion.type == "multiple_choice" ||
individualQuestion.type == "multiple_selection_choice"
) {
selectionList.innerHTML = ""; //reset choices list
for (j in individualQuestion.answers) {
let radioBtnName = "question" + qNum + "_choice";
let choiceText = individualQuestion.answers[j].answer;
selectionList.appendChild(createLi(radioBtnName, choiceText));
}
} else if (
individualQuestion.type == "long_text" ||
individualQuestion.type == "description"
) {
selectionList.innerHTML = "";
long.classList.toggle("hidden");
long.classList.add("current");
long.placeholder = "your reason here";
} else if (individualQuestion.type == "true_false") {
selectionList.innerHTML = "";
bool.appendChild(createLi("bool", "True"));
bool.appendChild(createLi("bool", "True"));
}
}
if (individualQuestion.type == "short_answer") { //multiple choice
selectionList.innerHTML = ""; function createLi(name, choiceText) {
short.classList.toggle("hidden"); let e = document.createElement("li");
short.classList.add("current"); let radioHtml =
short.placeholder = "your reason here"; '<input value="' + choiceText + '" type="radio" name="' + name + '"';
} else if ( radioHtml += "/>";
individualQuestion.type == "multiple_choice" || radioHtml += choiceText;
individualQuestion.type == "multiple_selection_choice" e.innerHTML = radioHtml;
) { return e;
selectionList.innerHTML = ""; //reset choices list }
for (j in individualQuestion.answers) {
let radioBtnName = "question" + qNum + "_choice";
let choiceText = individualQuestion.answers[j].answer;
selectionList.appendChild(createLi(radioBtnName, choiceText));
}
} else if (
individualQuestion.type == "long_text" ||
individualQuestion.type == "description"
) {
selectionList.innerHTML = "";
long.classList.toggle("hidden");
long.classList.add("current");
long.placeholder = "your reason here";
} else if (individualQuestion.type == "true_false") {
selectionList.innerHTML = "";
bool.appendChild(createLi("bool", "True"));
bool.appendChild(createLi("bool", "True"));
}
}
//multiple choice
function createLi(name, choiceText) {
let e = document.createElement("li");
let radioHtml =
'<input value="' + choiceText + '" type="radio" name="' + name + '"';
radioHtml += "/>";
radioHtml += choiceText;
e.innerHTML = radioHtml;
return e;
}
//call function at the beginning
populateQuestion(i);
//call function at the beginning
populateQuestion(i);
</script> </script>
</body> </body>
</html> </html>
+32 -3
View File
@@ -1,9 +1,38 @@
var express = require('express'); var express = require("express");
var router = express.Router(); var router = express.Router();
const db = require("../models");
const path = require("path");
/* GET home page. */ /* GET home page. */
router.get('/', function(req, res, next) { router.get("/", function (req, res, next) {
res.render('index', { title: 'Express' }); res.render("index", { title: "Express" });
});
// API endpoint to get quiz and questions
router.get("/api/quiz", async function (req, res) {
try {
const quiz = await db.quiz.findOne({
include: [{ model: db.question, as: "questions" }],
});
if (!quiz) {
return res.json({ success: false, error: "Quiz not found" });
}
// Parse options from JSON string to array for each question
const quizData = quiz.toJSON();
quizData.questions = quizData.questions.map((q) => ({
...q,
options:
typeof q.options === "string" ? JSON.parse(q.options) : q.options,
}));
res.json({ success: true, data: quizData });
} catch (err) {
res.json({ success: false, error: err.message });
}
});
// Serve quiz.html at /quiz
router.get("/quiz", function (req, res) {
res.sendFile(path.join(__dirname, "../quiz.html"));
}); });
module.exports = router; module.exports = router;
+39
View File
@@ -0,0 +1,39 @@
const db = require("./models/index");
async function seed() {
await db.sequelize.sync({ force: true });
const quiz = await db.quiz.create({
title: "JavaScript Basics",
description: "A quiz on JavaScript fundamentals.",
});
await db.question.bulkCreate([
{
quizId: quiz.id,
questionText: 'What is the output of 1 + "2" in JavaScript?',
options: JSON.stringify(["3", "12", "NaN", "Error"]),
answer: "12",
},
{
quizId: quiz.id,
questionText: "Which company developed JavaScript?",
options: JSON.stringify(["Netscape", "Microsoft", "Google", "Apple"]),
answer: "Netscape",
},
{
quizId: quiz.id,
questionText: "What keyword declares a variable in JavaScript?",
options: JSON.stringify(["var", "let", "const", "All of the above"]),
answer: "All of the above",
},
]);
console.log("Database seeded!");
process.exit();
}
seed().catch((err) => {
console.error(err);
process.exit(1);
});