import express from "express";
import bodyParser from "body-parser";
import pg from "pg";
const app = express();
const port = 3000;
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
const db = new pg.Client({
user:"postgres",
host: "localhost",
database: "permalist",
password: "password",
port:5432,
})
db.connect();
let items = [];
app.get("/", async (req, res) => { // await는 async에서 사용가능
const temp = await db.query("SELECT * FROM items ORDER BY id ASC");
items = temp.rows;
res.render("index.ejs", {
listTitle: "Today",
listItems: items,
});
});
app.post("/add", async (req, res) => {
const item = req.body.newItem;
// items.push({ title: item });
await db.query("INSERT INTO items (title) VALUES ($1)", [item]);
res.redirect("/");
});
app.post("/edit", async (req, res) => {
// const updatedItemId = req.body.updatedItemId;
// const searchIndex = items.findIndex((item) => item.id == updatedItemId);
// items[searchIndex].title = req.body.updatedItemTitle;
await db.query("UPDATE items SET title = $1 WHERE id = $2", [req.body.updatedItemTitle, req.body.updatedItemId]);
res.redirect("/");
});
app.post("/delete", async (req, res) => {
// const deleteItemId = req.body.deleteItemId;
// const searchIndex = items.findIndex((item) => item.id == deleteItemId);
// items.splice(searchIndex, 1);
await db.query("DELETE FROM items WHERE id = $1", [req.body.deleteItemId]);
res.redirect("/");
});
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});