Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
101 lines (82 loc) · 2.57 KB
/
Copy pathindex.js
File metadata and controls
101 lines (82 loc) · 2.57 KB
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
import express from "express";
import bodyParser from "body-parser";
import pg from "pg";
import axios from "axios";
// Create Express app
const app = express();
const port = 3000;
// Middleware setup
app.use(express.static("public")); // CSS aur images serve karne ke liye
app.use(bodyParser.urlencoded({ extended: true })); // HTML form ka data read karne ke liye
// Set EJS as the templating engine
app.set("view engine", "ejs");
// PostgreSQL database connection setup
const db = new pg.Client({
user: "postgres",
host: "localhost",
database: "My books",
password: "10256",
port: 5434,
});
// Connect to the database
db.connect()
.then(() => console.log("Database connected successfully! 🎉"))
.catch((err) => console.error("Database connection error ❌", err.stack));
// Home Route - Display Books
app.get("/", async (req, res) => {
try {
const result = await db.query("SELECT * FROM book ORDER BY rating DESC");
const books = result.rows;
res.render("index.ejs", {
title: "My Book Notes",
listItems: books
});
} catch (error) {
console.log(error);
res.status(500).send("Error fetching books from database");
}
});
// Add New Book Route
app.post("/add", async (req, res) => {
const { title, author, rating, date_read, isbn, notes } = req.body;
try {
await db.query(
"INSERT INTO book (title, author, rating, date_read, isbn, notes) VALUES ($1, $2, $3, $4, $5, $6)",
[title, author, rating, date_read, isbn, notes]
);
res.redirect("/");
} catch (error) {
console.log("Error inserting data:", error);
res.status(500).send("Error adding book to the database.");
}
});
// Delete Book Route
app.post("/delete", async (req, res) => {
const deleteId = req.body.deleteItemId;
try {
await db.query("DELETE FROM books WHERE id = $1", [deleteId]);
res.redirect("/");
} catch (error) {
console.log("Error deleting data:", error);
res.status(500).send("Error deleting the book.");
}
});
// Edit/Update Book Route
app.post("/edit", async (req, res) => {
const id = req.body.updateItemId;
const newRating = req.body.updatedRating;
const newNotes = req.body.updatedNotes;
try {
await db.query(
"UPDATE book SET rating = $1, notes = $2 WHERE id = $3",
[newRating, newNotes, id]
);
res.redirect("/");
} catch (error) {
console.log("Error updating data:", error);
res.status(500).send("Error updating the book.");
}
});
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});