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: "password",
port:5432,
});
db.connect();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
// function checkCountry(addCode) {
// }
app.get("/", async (req, res) => {
const result = await db.query("SELECT country_code FROM visited_countries");
let countries = [];
result.rows.forEach((country) => {
countries.push(country.country_code);
});
res.render("index.ejs", { countries: countries, total: countries.length });
});
app.post("/add", async (req, res) => {
const input = req.body["country"];
console.log(input);
var addCode = "";
const countryList = await db.query("SELECT country_name, country_code FROM countries");
countryList.rows.forEach((ele) => {
if(ele.country_name.toUpperCase() === input.toUpperCase()) {
addCode = ele.country_code;
} else {
;
}
})
if(addCode !== "") {
await db.query("INSERT INTO visited_countries(country_code) VALUES($1)", [addCode]);
} else {
console.log("Invalid country name. Please type correctly.");
}
res.redirect("/");
})
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});