-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
75 lines (63 loc) · 1.53 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
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: "permalist",
password: "****",
port: 5432,
});
db.connect();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
let items = [
{ id: 1, title: "Buy milk" },
{ id: 2, title: "Finish homework" },
];
app.get("/", async (req, res) => {
try {
const result = await db.query("SELECT * FROM items ORDER BY id ASC");
items = result.rows;
res.render("index.ejs", {
listTitle: "Today",
listItems: items,
});
} catch (err) {
console.log(err);
}
});
app.post("/add", async (req, res) => {
const item = req.body.newItem;
// items.push({title: item});
try {
await db.query("INSERT INTO items (title) VALUES ($1)", [item]);
res.redirect("/");
} catch (err) {
console.log(err);
}
});
app.post("/edit", async (req, res) => {
const item = req.body.updatedItemTitle;
const id = req.body.updatedItemId;
try {
await db.query("UPDATE items SET title = ($1) WHERE id = $2", [item, id]);
res.redirect("/");
} catch (err) {
console.log(err);
}
});
app.post("/delete", async (req, res) => {
const id = req.body.deleteItemId;
try {
await db.query("DELETE FROM items WHERE id = $1", [id]);
res.redirect("/");
} catch (err) {
console.log(err);
}
});
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});