-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
110 lines (103 loc) · 2.56 KB
/
app.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
const express = require("express");
const path = require("path");
require("dotenv").config();
const { Client } = require("pg");
const app = express();
//configure middlewares
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, "public")));
// set up routers
app.get("/", (req, res, next) => {
const client = new Client();
client
.connect()
.then(() => {
console.log("connection established");
const sql = "SELECT * FROM books ORDER BY books";
return client.query(sql).then(result => {
res.json(result.rows);
});
})
.catch(err => {
console.log("error ", err);
});
});
app.post("/", (req, res) => {
const { book, author } = req.body;
const client = new Client();
client
.connect()
.then(() => {
sql = "INSERT INTO books (book, author) VALUES ($1, $2)";
params = [book, author];
return client.query(sql, params);
})
.then(result => {
res.redirect("/");
})
.catch(err => {
console.error("Error found: ", err);
});
});
app.post("/:id/update", (req, res) => {
const { book, author } = req.body;
const id = req.params.id;
const client = new Client();
client
.connect()
.then(() => {
const sql =
"UPDATE books SET book = $1, author = $2 WHERE book_id = $3;";
const params = [book, author, id];
return client.query(sql, params);
})
.then(result => {
res.redirect("/");
})
.catch(err => {
console.log("error: ", err);
});
});
app.get("/:id", (req, res) => {
const id = req.params.id;
const client = new Client();
client
.connect()
.then(() => {
const sql = "SELECT * FROM books where book_id = $1;";
params = [id];
return client.query(sql, params);
})
.then(result => {
if (result.rows.length === 0) {
res.json({
message: "your book cannot be found!"
});
}
res.json(result.rows);
})
.catch(err => {
console.error("Error found :", err);
});
});
app.post("/:id/delete", (req, res) => {
const client = new Client();
client
.connect()
.then(() => {
const sql = "DELETE FROM books where book_id = $1;";
const params = [req.params.id];
return client.query(sql, params);
})
.then(result => {
res.redirect("/");
})
.catch(err => {
console.log("Error encoutered: ", err);
});
});
//const port = 4000;
app.listen(process.env.PORT, () => {
console.log(`Server started at port ${process.env.PORT}`);
});