-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
78 lines (65 loc) · 1.58 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
import express from "express";
import bodyParser from "body-parser";
import pg from "pg"
const db = new pg.Client({
user: "postgres",
host: "localhost",
database: "your db name",
password: "your password",
port: 5432,
});
const app = express();
const port = 3000;
db.connect();
let totalCorrect = 0;
// Middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
let quiz = []
db.query("SELECT * FROM flags", (err, res) => {
if (err) {
console.error("Error executing query", err.stack);
} else {
quiz = res.rows;
}
db.end();
});
let currentQuestion = {};
// GET home page
app.get("/", (req, res) => {
totalCorrect = 0;
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.name.toLowerCase() === answer.toLowerCase()) {
totalCorrect++;
console.log(totalCorrect);
isCorrect = true;
}
nextQuestion();
res.render("index.ejs", {
question: currentQuestion,
wasCorrect: isCorrect,
totalScore: totalCorrect,
});
});
app.post("/skip", (req, res) => {
nextQuestion()
res.render("index.ejs", {
question: currentQuestion,
wasCorrect: null,
totalScore: totalCorrect,
});
})
function nextQuestion() {
const randomCountry = quiz[Math.floor(Math.random() * quiz.length)];
currentQuestion = randomCountry;
}
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});