index.js
3.04 KB
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
module.exports = function(app, Book)
{
// GET ALL BOOKS
app.get('/api/books', function(req,res){
Book.find(function(err, books){
if(err) return res.status(500).send({error: 'database failure'});
res.json(books);
})
});
// GET SINGLE BOOK
app.get('/api/books/:book_id', function(req, res){
Book.findOne({_id: req.params.book_id}, function(err, book){
if(err) return res.status(500).json({error: err});
if(!book) return res.status(404).json({error: 'book not found'});
res.json(book);
})
});
// GET BOOK BY AUTHOR
app.get('/api/books/author/:author', function(req, res){
Book.find({author: req.params.author}, {_id: 0, title: 1, published_date: 1}, function(err, books){
if(err) return res.status(500).json({error: err});
if(books.length === 0) return res.status(404).json({error: 'book not found'});
res.json(books);
})
});
// CREATE BOOK
app.post('/api/books', function(req, res){
var book = new Book();
book.title = req.body.title;
book.author = req.body.author;
book.published_date = new Date(req.body.published_date);
book.save(function(err){
if(err){
console.error(err);
res.json({result: 0});
return;
}
res.json({result: 1});
});
});
// UPDATE THE BOOK
app.put('/api/books/:book_id', function(req, res){
Book.update({ _id: req.params.book_id }, { $set: req.body }, function(err, output){
if(err) res.status(500).json({ error: 'database failure' });
console.log(output);
if(!output.n) return res.status(404).json({ error: 'book not found' });
res.json( { message: 'book updated' } );
})
/* [ ANOTHER WAY TO UPDATE THE BOOK ]
Book.findById(req.params.book_id, function(err, book){
if(err) return res.status(500).json({ error: 'database failure' });
if(!book) return res.status(404).json({ error: 'book not found' });
if(req.body.title) book.title = req.body.title;
if(req.body.author) book.author = req.body.author;
if(req.body.published_date) book.published_date = req.body.published_date;
book.save(function(err){
if(err) res.status(500).json({error: 'failed to update'});
res.json({message: 'book updated'});
});
});
*/
});
// DELETE BOOK
app.delete('/api/books/:book_id', function(req, res){
Book.remove({ _id: req.params.book_id }, function(err, output){
if(err) return res.status(500).json({ error: "database failure" });
/* ( SINCE DELETE OPERATION IS IDEMPOTENT, NO NEED TO SPECIFY )
if(!output.result.n) return res.status(404).json({ error: "book not found" });
res.json({ message: "book deleted" });
*/
res.status(204).end();
})
});
}