feat: complete day 8
This commit is contained in:
+30
-16
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
};
|
||||
@@ -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
@@ -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",
|
||||
|
||||
+41
-69
@@ -1,11 +1,10 @@
|
||||
|
||||
<!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">
|
||||
<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");
|
||||
@@ -81,83 +80,57 @@ input:focus {
|
||||
margin-top: 30px;
|
||||
color: teal;
|
||||
}
|
||||
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<div class="main">
|
||||
|
||||
|
||||
<h1>Quiz</h1>
|
||||
<div id="yourAnswers" class="hidden">
|
||||
<h1>Your answers</h1>
|
||||
<pre id="answerObject"></pre>
|
||||
</div>
|
||||
<div class="question" id="questionsDiv">
|
||||
|
||||
<h2 id="title"></h2>
|
||||
<ul id ='selectionList'> </ul>
|
||||
<ul id="selectionList"></ul>
|
||||
<input id="short" type="text" class="hidden" />
|
||||
<textarea name="" id="long" class="hidden" cols="30" rows="10"></textarea>
|
||||
<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");
|
||||
@@ -167,9 +140,6 @@ let inp = document.getElementById("short");
|
||||
let text = document.getElementById("long");
|
||||
let yourAnswers = document.getElementById("yourAnswers");
|
||||
let questionsDiv = document.getElementById("questionsDiv");
|
||||
let i = 0;
|
||||
|
||||
let answers = {};
|
||||
|
||||
//step
|
||||
nextButton.onclick = function () {
|
||||
@@ -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;
|
||||
@@ -271,7 +244,6 @@ function createLi(name, choiceText) {
|
||||
|
||||
//call function at the beginning
|
||||
populateQuestion(i);
|
||||
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+32
-3
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
Reference in New Issue
Block a user