-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution4.js
74 lines (66 loc) · 1.85 KB
/
solution4.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
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: "Sanchit@9811",
port: 5432,
});
db.connect();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
async function checkVisisted() {
const result = await db.query("SELECT country_code FROM visited_countries");
let countries = [];
result.rows.forEach((country) => {
countries.push(country.country_code);
});
return countries;
}
// GET home page
app.get("/", async (req, res) => {
const countries = await checkVisisted();
res.render("index.ejs", { countries: countries, total: countries.length });
});
//INSERT new country
app.post("/add", async (req, res) => {
const input = req.body["country"];
try {
const result = await db.query(
"SELECT country_code FROM countries WHERE LOWER(country_name) LIKE '%' || $1 || '%';",
[input.toLowerCase()]
);
const data = result.rows[0];
const countryCode = data.country_code;
try {
await db.query(
"INSERT INTO visited_countries (country_code) VALUES ($1)",
[countryCode]
);
res.redirect("/");
} catch (err) {
console.log(err);
const countries = await checkVisisted();
res.render("index.ejs", {
countries: countries,
total: countries.length,
error: "Country has already been added, try again.",
});
}
} catch (err) {
console.log(err);
const countries = await checkVisisted();
res.render("index.ejs", {
countries: countries,
total: countries.length,
error: "Country name does not exist, try again.",
});
}
});
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});