-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
89 lines (70 loc) · 1.84 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import express from "express";
import bodyParser from "body-parser";
import pg from "pg";
const db = new pg.Client({
user: "postgres", //PostgreSQL default
host: "localhost", //PostgreSQL default
database: "your database name",
password: "your PostgreSQL password",
port: 5432, //PostgreSQL default
});
const app = express();
const port = 3000;
db.connect();
let quiz = [];
db.query("SELECT * FROM capitals", (err, res) => {
if (err) {
console.error("Error executing query", err.stack)
} else {
quiz = res.rows
}
db.end()
})
let totalCorrect = 0;
// Middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
let currentQuestion = {};
// GET home page
app.get("/", async (req, res) => {
totalCorrect = 0;
await nextQuestion();
console.log(currentQuestion);
res.render("index.ejs", { question: currentQuestion });
});
// POST a new post
app.post("/submit", (req, res) => {
let answer = req.body.answer.trim();
let isCorrect = false;
if (currentQuestion.capital.toLowerCase() === answer.toLowerCase()) {
totalCorrect++;
console.log(totalCorrect);
isCorrect = true;
}
nextQuestion();
res.render("index.ejs", {
question: currentQuestion,
wasCorrect: isCorrect,
totalScore: totalCorrect,
});
});
//Skip btn function
app.post("/skip", (req, res) => {
nextQuestion()
res.render("index.ejs", {
question: currentQuestion,
wasCorrect: null,
totalScore: totalCorrect,
});
})
async function nextQuestion() {
const randomCountry = quiz[Math.floor(Math.random() * quiz.length)];
currentQuestion = randomCountry;
}
async function skipQuestion() {
const randomCountry = quiz[Math.floor(Math.random() * quiz.length)];
currentQuestion = randomCountry;
};
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});