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
+30 -16
View File
@@ -1,4 +1,4 @@
'use strict';
"use strict";
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2020*/
/**
* Sequelize File
@@ -8,24 +8,28 @@
* @author Ryan Wong
*
*/
const fs = require('fs');
const path = require('path');
let Sequelize = require('sequelize');
const fs = require("fs");
const path = require("path");
let Sequelize = require("sequelize");
const basename = path.basename(__filename);
const { DataTypes } = require('sequelize');
const { DataTypes } = require("sequelize");
const config = {
DB_DATABASE: 'mysql',
DB_USERNAME: 'root',
DB_PASSWORD: 'root',
DB_ADAPTER: 'mysql',
DB_NAME: 'day_1',
DB_HOSTNAME: 'localhost',
DB_DATABASE: "mysql",
DB_USERNAME: "root",
DB_PASSWORD: process.env.DB_PASSWORD || "root",
DB_ADAPTER: "mysql",
DB_NAME: "day_8",
DB_HOSTNAME: "localhost",
DB_PORT: 3306,
};
let db = {};
let sequelize = new Sequelize(config.DB_DATABASE, config.DB_USERNAME, config.DB_PASSWORD, {
let sequelize = new Sequelize(
config.DB_NAME,
config.DB_USERNAME,
config.DB_PASSWORD,
{
dialect: config.DB_ADAPTER,
username: config.DB_USERNAME,
password: config.DB_PASSWORD,
@@ -33,7 +37,7 @@ let sequelize = new Sequelize(config.DB_DATABASE, config.DB_USERNAME, config.DB_
host: config.DB_HOSTNAME,
port: config.DB_PORT,
logging: console.log,
timezone: '-04:00',
timezone: "-04:00",
pool: {
maxConnections: 1,
minConnections: 0,
@@ -44,13 +48,23 @@ let sequelize = new Sequelize(config.DB_DATABASE, config.DB_USERNAME, config.DB_
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)
.filter((file) => {
return file.indexOf('.') !== 0 && file !== basename && file.slice(-3) === '.js';
return (
file.indexOf(".") !== 0 && file !== basename && file.slice(-3) === ".js"
);
})
.forEach((file) => {
var model = require(path.join(__dirname, file))(sequelize, DataTypes);
+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",
"private": true,
"scripts": {
"start": "node ./bin/www"
"start": "node ./bin/www",
"dev": "node --watch --env-file=.env ./bin/www"
},
"dependencies": {
"cookie-parser": "~1.4.4",
+93 -121
View File
@@ -1,29 +1,28 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./style.css">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="./style.css" />
<title>Quiz</title>
<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;
margin: 0;
padding: 0;
}
}
html,
body {
html,
body {
font-family: "Open Sans", sans-serif;
line-height: 1.4;
background-color: #333;
}
}
.main {
.main {
margin: 0 auto;
width: 600px;
margin-top: 200px;
@@ -34,145 +33,116 @@ body {
/* box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px; */
box-shadow: rgba(0, 0, 0, 0.05) 0px 6px 24px 0px,
rgba(0, 0, 0, 0.08) 0px 0px 0px 1px;
}
}
.hidden {
.hidden {
display: none;
}
}
button {
button {
padding: 10px;
border: 10px;
background-color: teal;
font-weight: bold;
color: white;
border-radius: 2px;
}
button:hover {
}
button:hover {
cursor: pointer;
}
input {
}
input {
margin: 10px;
border: none;
font-size: large;
color: rgba(0, 128, 128, 0.616);
}
textarea {
}
textarea {
border: none;
font-size: large;
color: rgba(0, 128, 128, 0.616);
}
ul {
}
ul {
list-style: none;
margin-bottom: 10px;
}
#bool {
}
#bool {
list-style: none;
display: flex;
flex-direction: row;
margin: 10px;
}
textarea:focus,
input:focus {
}
textarea:focus,
input:focus {
outline: none;
}
}
#yourAnswers p {
#yourAnswers p {
margin-top: 30px;
color: teal;
}
}
</style>
</head>
<body>
</head>
<body>
<div class="main">
<h1>Quiz</h1>
<div id="yourAnswers" class="hidden">
<h1 >Your answers</h1>
<h1>Your answers</h1>
<pre id="answerObject"></pre>
</div>
<div class="question" id="questionsDiv">
<h2 id="title"></h2>
<ul id ='selectionList'> </ul>
<input id="short" type="text" class="hidden"/>
<textarea name="" id="long" class="hidden" cols="30" rows="10"></textarea>
<ul id="selectionList"></ul>
<input id="short" type="text" class="hidden" />
<textarea
name=""
id="long"
class="hidden"
cols="30"
rows="10"
></textarea>
<div id="bool"></div>
<button id="next">Next</button>
</div>
</div>
<script>
let quiz = [
{
id: 1,
type: "short_answer",
question: "Why is the sky blue?",
answers: [],
correct_answer: 0,
},
{
id: 2,
type: "multiple_choice",
question: "Why is the sky blue?",
answers: [
{ 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: 3,
type: "multiple_selection_choice",
question: "Why is the sky blue?",
answers: [
{ 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,
},
];
// Fetch quiz data from API
fetch("/api/quiz")
.then((res) => res.json())
.then((result) => {
if (result.success) {
// Transform API data to match expected quiz array structure
const apiQuiz = result.data;
window.quiz = apiQuiz.questions.map((q, idx) => ({
id: q.id,
type: "multiple_choice", // You can enhance this to support more types if needed
question: q.questionText,
answers: q.options.map((opt, i) => ({ id: i + 1, answer: opt })),
correct_answer: q.answer,
}));
// Start quiz
window.i = 0;
window.answers = {};
populateQuestion(window.i);
} else {
alert("Failed to load quiz: " + result.error);
}
})
.catch((err) => {
alert("Error fetching quiz: " + err);
});
let nextButton = document.getElementById("next");
let title = document.getElementById("title");
let selectionList = document.getElementById("selectionList");
let bool = document.getElementById("bool");
let inp = document.getElementById("short");
let text = document.getElementById("long");
let yourAnswers = document.getElementById("yourAnswers");
let questionsDiv = document.getElementById("questionsDiv");
let i = 0;
let nextButton = document.getElementById("next");
let title = document.getElementById("title");
let selectionList = document.getElementById("selectionList");
let bool = document.getElementById("bool");
let inp = document.getElementById("short");
let text = document.getElementById("long");
let yourAnswers = document.getElementById("yourAnswers");
let questionsDiv = document.getElementById("questionsDiv");
let answers = {};
//step
nextButton.onclick = function () {
//step
nextButton.onclick = function () {
//get the answers
if (quiz[i].type == "short_answer") {
let x = document.getElementsByClassName("current")[0];
@@ -192,7 +162,10 @@ nextButton.onclick = function () {
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") {
} 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;
@@ -219,10 +192,10 @@ nextButton.onclick = function () {
return;
}
populateQuestion(i);
};
};
//generate question
function populateQuestion(qNum) {
//generate question
function populateQuestion(qNum) {
let individualQuestion = quiz[qNum];
title.innerText = individualQuestion.question;
@@ -256,10 +229,10 @@ function populateQuestion(qNum) {
bool.appendChild(createLi("bool", "True"));
bool.appendChild(createLi("bool", "True"));
}
}
}
//multiple choice
function createLi(name, choiceText) {
//multiple choice
function createLi(name, choiceText) {
let e = document.createElement("li");
let radioHtml =
'<input value="' + choiceText + '" type="radio" name="' + name + '"';
@@ -267,11 +240,10 @@ function createLi(name, choiceText) {
radioHtml += choiceText;
e.innerHTML = radioHtml;
return e;
}
//call function at the beginning
populateQuestion(i);
}
//call function at the beginning
populateQuestion(i);
</script>
</body>
</body>
</html>
+32 -3
View File
@@ -1,9 +1,38 @@
var express = require('express');
var express = require("express");
var router = express.Router();
const db = require("../models");
const path = require("path");
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
router.get("/", function (req, res, next) {
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;
+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);
});