-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.js
107 lines (91 loc) · 2.43 KB
/
solution.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
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: "123456",
port: 5432,
});
db.connect();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
let currentUserId = 1;
let users = [
{ id: 1, name: "Angela", color: "teal" },
{ id: 2, name: "Jack", color: "powderblue" },
];
async function checkVisisted() {
const result = await db.query(
"SELECT country_code FROM visited_countries JOIN users ON users.id = user_id WHERE user_id = $1; ",
[currentUserId]
);
let countries = [];
result.rows.forEach((country) => {
countries.push(country.country_code);
});
return countries;
}
async function getCurrentUser() {
const result = await db.query("SELECT * FROM users");
users = result.rows;
return users.find((user) => user.id == currentUserId);
}
app.get("/", async (req, res) => {
const countries = await checkVisisted();
const currentUser = await getCurrentUser();
res.render("index.ejs", {
countries: countries,
total: countries.length,
users: users,
color: currentUser.color,
});
});
app.post("/add", async (req, res) => {
const input = req.body["country"];
const currentUser = await getCurrentUser();
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, user_id) VALUES ($1, $2)",
[countryCode, currentUserId]
);
res.redirect("/");
} catch (err) {
console.log(err);
}
} catch (err) {
console.log(err);
}
});
app.post("/user", async (req, res) => {
if (req.body.add === "new") {
res.render("new.ejs");
} else {
currentUserId = req.body.user;
res.redirect("/");
}
});
app.post("/new", async (req, res) => {
const name = req.body.name;
const color = req.body.color;
const result = await db.query(
"INSERT INTO users (name, color) VALUES($1, $2) RETURNING *;",
[name, color]
);
const id = result.rows[0].id;
currentUserId = id;
res.redirect("/");
});
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});