-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
145 lines (120 loc) · 3.89 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
import express from "express";
import dotenv from "dotenv";
import pool from "./config/dbPool.js";
dotenv.config();
const app = express();
const port = process.env.PORT || 3000;
app.use(express.urlencoded({ extended: true }));
app.use(express.static("public"));
// Store active user ID to track the current session context (in-memory state)
let activeUserId = 1;
// General error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send("Something went wrong. Please try again later.");
});
// Fetch users from the database
const fetchUsers = async () => (await pool.query("SELECT * FROM users")).rows;
// Fetch visited countries for a given user ID
const checkVisited = async (userId) =>
(
await pool.query(
"SELECT country_code FROM visited_countries WHERE user_id = $1",
[userId]
)
).rows.map((row) => row.country_code);
// Helper function to render the home page
const renderHomePage = async (res, options = {}) => {
try {
const users = await fetchUsers();
const currentUser = users.find((user) => user.id === activeUserId);
const countries = await checkVisited(activeUserId);
res.render("pages/index.ejs", {
countries,
total: countries.length,
users,
color: currentUser ? currentUser.color : "teal",
...options,
});
} catch (err) {
res.status(500).send("Error rendering the home page.");
}
};
// GET home page
app.get("/", (req, res) => renderHomePage(res));
// POST route to switch users or add a new user
app.post("/user", (req, res) => {
if (req.body.add) {
return res.render("pages/new.ejs");
}
const userId = req.body.user;
activeUserId = userId;
renderHomePage(res);
});
// POST route to add a new country for a user
app.post("/add", async (req, res) => {
const input = req.body.country_input.trim();
try {
// Search for the country by name
const countryResult = await pool.query(
"SELECT country_code, country_name FROM countries WHERE country_name ILIKE '%' || $1 || '%';",
[input]
);
if (countryResult.rowCount === 0) {
return renderHomePage(res, {
error: "Country not found. Please try again.",
});
}
const rows = countryResult.rows;
const exactMatch = rows.find(
(row) => row.country_name.toLowerCase() === input.toLowerCase()
);
const countryCode = exactMatch
? exactMatch.country_code
: rows[0].country_code;
// Check if the country is already added for this user
const checkResult = await pool.query(
"SELECT 1 FROM visited_countries WHERE user_id = $1 AND country_code = $2",
[activeUserId, countryCode]
);
if (checkResult.rowCount > 0) {
return renderHomePage(res, {
error: "Country has already been added. Please try a different one.",
});
}
// Insert the visited country for the active user
await pool.query(
"INSERT INTO visited_countries (country_code, user_id) VALUES ($1, $2)",
[countryCode, activeUserId]
);
renderHomePage(res);
} catch (err) {
res.status(500).send("Error adding the country.");
}
});
// POST route for adding a new user
app.post("/new", async (req, res) => {
const userName = req.body.name
.trim()
.toLowerCase()
.replace(/^./, (str) => str.toUpperCase());
const userColor = req.body.color;
try {
// Insert the new user and use RETURNING to get the inserted user data
const result = await pool.query(
"INSERT INTO users (name, color) VALUES ($1, $2) ON CONFLICT DO NOTHING RETURNING *",
[userName, userColor]
);
if (result.rowCount > 0) {
const newUser = result.rows[0];
activeUserId = newUser.id;
return renderHomePage(res);
}
res.redirect("/");
} catch (err) {
res.status(500).send("Error adding the new user.");
}
});
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});