-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsever.js
84 lines (67 loc) · 1.91 KB
/
sever.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
import express from "express";
import pg from "pg";
import dotenv from "dotenv";
import cors from 'cors';
dotenv.config();
// const { DATABASE_URL, PORT } = .env;
const app = express();
const PORT = 3000;
const db = new pg.Pool({
connectionString: process.env.DATABASE_URL,
user: "leo",
host: "localhost",
database: 'todo',
password: 'Uglyg00d',
port: "5432"
});
app.use(express.static("./public"));
app.use(express.json());
app.use(cors());
app.get("http://localhost:3000/api/todo", (_, res) => {
db.query("SELECT * FROM todo").then((data) => {
res.json(data.rows);
});
});
app.delete("http://localhost:3000/api/todo/:id", (req, res) => {
const id = req.params.id;
if (Number.isNaN(Number(id))) {
res.sendStatus(422);
return;
}
const query = "DELETE FROM todo WHERE id = $1 RETURNING *";
const values = [id];
db.query(query, values)
.then((data) => {
console.log("hello");
if (data.rows.length === 0) {
res.sendStatus(404); // Not Found
} else {
res.sendStatus(204); // No Content
}
})
.catch((error) => {
console.error("Error executing DELETE query:", error);
res.sendStatus(500); // Internal Server Error
});
});
app.patch("http://localhost:3000/api/todo/:id", (req, res) => {
const { id } = req.params;
const { text } = req.body;
db.query("UPDATE todo SET text = $1 WHERE id = $2 RETURNING *", [
text,
id,
]).then((data) => {
res.send(data.rows[0]);
});
});
app.post("http://localhost:3000/api/todo", (req, res) => {
const { text } = req.body;
db.query("INSERT INTO todo (text) VALUES ($1) RETURNING *", [
text
]).then((result) => {
res.send(result.rows[0]);
})
});
app.listen(PORT, () => {
console.log(`Listening on port: ${PORT}`)
})