forked from Gregorio-Moreta/express-mongoose-bookmarks-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
71 lines (57 loc) · 1.88 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
import express from 'express'
import connection from './lib/db/connection.js';
import Bookmark from './models/Bookmark.js';
import * as dotenv from 'dotenv'
// const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017/bookmarks'
const PORT = process.env.PORT || 4000
dotenv.config()
const app = express();
// FIND ALL BOOKMARKS
app.get("/", function(req, res) {
Bookmark.find({}).then(bookmarks => res.json(bookmarks));
});
app.get("/test", (request, response) => {
response.send("Test" + " Test");
});
// FIND ONE BOOKMARK
app.get("/bookmarks/:id", function(req, res) {
Bookmark.findById(req.params.id)
.then(bookmark => {
if (!bookmark) {
return res.status(404).json({ error: "Bookmark not found" });
}
res.json(bookmark);
})
.catch(error => res.status(500).json({ error: "Server error" }));
});
// CREATE A BOOKMARK
app.post("/bookmarks", function(req, res) {
Bookmark.create(req.body)
.then(bookmark => res.status(201).json(bookmark))
.catch(error => res.status(500).json({ error: "Server error" }));
});
// DELETE A BOOKMARK
app.delete("/bookmarks/:id", function(req, res) {
Bookmark.findByIdAndRemove(req.params.id)
.then(bookmark => {
if (!bookmark) {
return res.status(404).json({ error: "Bookmark not found" });
}
res.json({ message: "Bookmark deleted successfully" });
})
.catch(error => res.status(500).json({ error: "Server error" }));
});
// UPDATE A BOOKMARK
app.put("/bookmarks/:id", function(req, res) {
Bookmark.findByIdAndUpdate(req.params.id, req.body, { new: true })
.then(bookmark => {
if (!bookmark) {
return res.status(404).json({ error: "Bookmark not found" });
}
res.json(bookmark);
})
.catch(error => res.status(500).json({ error: "Server error" }));
});
app.listen(PORT, () => {
console.log(`Server is listening on PORT: ${PORT}`);
});