This commit is contained in:
ryanwong
2022-02-06 21:30:08 -05:00
parent dfbe8721b4
commit 55fd966174
14 changed files with 579 additions and 0 deletions
Vendored
BIN
View File
Binary file not shown.
+11
View File
@@ -0,0 +1,11 @@
# day 8
## Instructions
- setup project
- clone to your github
- Read the documentation https://sequelize.org/v7/manual/getting-started.html
- Setup the models you think you need.
- Look at quiz.html. Integrate that into your express application. Make the quiz object come from api not hardcode it
- Everything must be done by end of date
+44
View File
@@ -0,0 +1,44 @@
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
const db = require("./models");
var cors = require("cors");
var app = express();
app.set("db", db);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(cors());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Executable
+90
View File
@@ -0,0 +1,90 @@
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('day-1:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
+68
View File
@@ -0,0 +1,68 @@
'use strict';
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2020*/
/**
* Sequelize File
* @copyright 2020 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*
*/
const fs = require('fs');
const path = require('path');
let Sequelize = require('sequelize');
const basename = path.basename(__filename);
const config = {
DB_DATABASE: 'mysql',
DB_USERNAME: 'root',
DB_PASSWORD: 'root',
DB_ADAPTER: 'mysql',
DB_NAME: 'day_1',
DB_HOSTNAME: 'localhost',
DB_PORT: 3306,
};
let db = {};
let sequelize = new Sequelize(config.DB_DATABASE, config.DB_USERNAME, config.DB_PASSWORD, {
dialect: config.DB_ADAPTER,
username: config.DB_USERNAME,
password: config.DB_PASSWORD,
database: config.DB_NAME,
host: config.DB_HOSTNAME,
port: config.DB_PORT,
logging: console.log,
timezone: '-04:00',
pool: {
maxConnections: 1,
minConnections: 0,
maxIdleTime: 100,
},
define: {
timestamps: false,
underscoredAll: true,
underscored: true,
},
});
// sequelize.sync({ force: true });
fs.readdirSync(__dirname)
.filter((file) => {
return file.indexOf('.') !== 0 && file !== basename && file.slice(-3) === '.js';
})
.forEach((file) => {
var model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach((modelName) => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
+26
View File
@@ -0,0 +1,26 @@
module.exports = (sequelize, DataTypes) => {
const location = sequelize.define(
"location",
{
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
name: DataTypes.STRING,
created_at: DataTypes.DATEONLY,
updated_at: DataTypes.DATE,
},
{
timestamps: true,
freezeTableName: true,
tableName: "location",
},
{
underscoredAll: false,
underscored: false,
}
);
return location;
};
+19
View File
@@ -0,0 +1,19 @@
{
"name": "day-1",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"cookie-parser": "~1.4.4",
"cors": "^2.8.5",
"debug": "~2.6.9",
"express": "~4.16.1",
"http-errors": "~1.6.3",
"jade": "~1.11.0",
"morgan": "~1.9.1",
"mysql2": "^2.3.3",
"sequelize": "^6.15.1"
}
}
+8
View File
@@ -0,0 +1,8 @@
body {
padding: 50px;
font: 14px "Lucida Grande", Helvetica, Arial, sans-serif;
}
a {
color: #00B7FF;
}
+277
View File
@@ -0,0 +1,277 @@
<!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">
<title>Quiz</title>
<style>
@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 {
font-family: "Open Sans", sans-serif;
line-height: 1.4;
background-color: #333;
}
.main {
margin: 0 auto;
width: 600px;
margin-top: 200px;
background-color: white;
padding: 20px;
border-radius: 10px;
/* 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 {
display: none;
}
button {
padding: 10px;
border: 10px;
background-color: teal;
font-weight: bold;
color: white;
border-radius: 2px;
}
button:hover {
cursor: pointer;
}
input {
margin: 10px;
border: none;
font-size: large;
color: rgba(0, 128, 128, 0.616);
}
textarea {
border: none;
font-size: large;
color: rgba(0, 128, 128, 0.616);
}
ul {
list-style: none;
margin-bottom: 10px;
}
#bool {
list-style: none;
display: flex;
flex-direction: row;
margin: 10px;
}
textarea:focus,
input:focus {
outline: none;
}
#yourAnswers p {
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>
<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,
},
];
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 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);
};
//generate 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"));
}
}
//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);
</script>
</body>
</html>
+9
View File
@@ -0,0 +1,9 @@
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
+9
View File
@@ -0,0 +1,9 @@
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = router;
+6
View File
@@ -0,0 +1,6 @@
extends layout
block content
h1= message
h2= error.status
pre #{error.stack}
+5
View File
@@ -0,0 +1,5 @@
extends layout
block content
h1= title
p Welcome to #{title}
+7
View File
@@ -0,0 +1,7 @@
doctype html
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
body
block content