-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
93 lines (87 loc) · 2.25 KB
/
server.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
const path = require("path");
const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");
const Database = require("./Database");
console.log(path.join(__dirname, "public"));
const app = express();
const db = new Database();
app.use(cors()); // api call from outsidethe server
// ease of use of app in the client
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, "public")));
// api post create note
app.post("/notes", (req, res) => {
const body = req.body;
console.log("body", body);
db.addNote(body)
.then((data) => res.send(data))
.catch((err) => res.status(500).send(err));
});
// get
// app.get("/notes", (req, res) => {
// db.getNotes()
// .then((data) => res.send(data))
// .catch((err) => res.status(500).send(err));
// });
app.get("/notes", (req, res) => {
const { title } = req.query;
if (title) {
db.getNotesByTitle(title)
.then((data) => {
res.send(data);
})
.catch((error) => {
res.status(500).send(error);
});
} else {
db.getNotes()
.then((data) => {
res.send(data);
})
.catch((error) => {
res.status(500).send(error);
});
}
});
app.get("/notes/:id", (req, res) => {
const { id } = req.params;
db.getNoteById(id)
.then((data) => {
if (!data) {
res.status(404).send("note id does not exsit " + id);
} else {
res.send(data);
}
})
.catch((err) => res.status(500).send(err));
});
app.put("/notes", (req, res) => {
db.updateNote(req.body)
.then((data) => {
if (!data) {
res.status(404).send("note id does not exsit " + id);
} else {
res.send(data);
}
})
.catch((err) => res.status(500).send(err));
});
app.delete("/notes/:id", (req, res) => {
const { id } = req.params;
db.deleteNote(id)
.then((data) => {
if (!data) {
res.status(404).send("note id does not exsit " + id);
} else {
res.send(data);
}
})
.catch((err) => res.status(500).send(err));
});
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server has been listening on port : ${port}`);
db.connect();
});