-
Notifications
You must be signed in to change notification settings - Fork 0
/
bookmarks.js
92 lines (82 loc) · 2.31 KB
/
bookmarks.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
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/bookmarks');
var Bookmark = mongoose.model('Bookmark', { name: String, url: String });
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
console.log("Connected to 'bookmarks' database.");
});
exports.load = function(app) {
app.get('/bookmarks', function(req, res){
Bookmark.find(function (err, bookmarks) {
if (err) {
console.log(err);
}
console.log(bookmarks);
res.send(bookmarks);
});
});
app.post('/bookmark', function(req, res){
console.log("Request to add bookmark: " + req);
if(req.body && req.body.name && req.body.url) {
var name = req.body.name;
var url = req.body.url;
console.log("Adding bookmark: " + name + "-" + url);
var bookmark = new Bookmark({ name: name, url: url });
bookmark.save(function (err) {
if (err) {
console.log('Cannot add bookmark..');
}
});
res.send('Added Bookmark: '+ bookmark);
}
});
app.get('/bookmark/:id', function(req, res){
Bookmark.find({_id: req.params.id}, function (err, bookmarks) {
if (err) {
console.log(err);
}
console.log(bookmarks);
res.send(bookmarks);
});
});
app.put('/bookmark/:id', function(req, res){
if(req.body && ( req.body.name || req.body.url)) {
Bookmark.find({_id: req.params.id}, function (err, bookmarks) {
if (err) {
console.log(err);
}
console.log(bookmarks);
if(bookmarks.length > 0) {
var bookmark = bookmarks[0];
if(req.body.name) {
bookmark.name = req.body.name;
}
if(req.body.url) {
bookmark.url = req.body.url;
}
bookmark.save(function (err) {
if (err) {
console.log('Cannot update bookmark..');
}
});
res.send('Updated Bookmark: '+ bookmark);
}
});
}
});
app.delete('/bookmark/:id', function(req, res){
Bookmark.find({_id: req.params.id}, function (err, bookmarks) {
if (err) {
console.log(err);
}
console.log(bookmarks);
if(bookmarks.length > 0) {
var bookmark = bookmarks[0];
bookmark.remove();
res.send("Deleted: "+ bookmark);
}
});
});
console.log("'bookmarks' module loaded.");
}