-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
75 lines (61 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
import express from "express";
import bodyParser from "body-parser";
import pg from "pg";
const app = express();
const port = 3000;
const db = new pg.Client({
user: "postgres",
host: "localhost",
database: "world",
password: "shishir",
port: 5432,
});
db.connect();
let quiz = [
{ country: "France", capital: "Paris" },
{ country: "United Kingdom", capital: "London" },
{ country: "United States of America", capital: "New York" },
];
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,
});
});
async 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}`);
});