-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
95 lines (86 loc) · 2.51 KB
/
app.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
94
95
var express = require('express');
var mongoose = require('mongoose');
var Book = require('./book');
var app = express();
app.configure(function () {
app.use(express.bodyParser())
app.use(app.router)
});
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback() {
//select all
app.get('/book', function(req, res) {
var q = Book.find().sort('isbn').limit(req.query.limit).skip(req.query.skip);
q.execFind(function(err, doc) {
res.json(doc);
});
});
//select one
app.get('/book/:isbn', function(req, res) {
Book.findOne({ isbn: req.params.isbn}, function (err, doc){
if (err) {
res.json({error: 'book not found'});
} else {
res.json(doc);
}
});
});
//insert
app.post('/book', function(req, res) {
var newbook = new Book(req.body);
newbook.save(function(err) {
if (err) {
res.send(422,'insert failed');
} else {
res.json(newbook);
}
})
});
//update
app.put('/book/:isbn', function(req, res) {
Book.findOne({isbn: req.params.isbn}, function (err, book){
if (err) {
res.send(422,'update failed');
} else {
if (req.body.isbn !== undefined) {
//isbn change is not allowed
res.send(422,'update failed');
} else {
//update fields
for (var field in Book.schema.paths) {
if ((field !== 'isbn') && (field !== '_id') && (field !== '__v')) {
if (req.body[field] !== undefined) {
book[field] = req.body[field];
}
}
}
book.save(function(err){
if (err) {
res.send(422,'update failed');
} else {
res.json(book);
}
});
}
}
});
});
//delete
app.del('/book/:isbn', function(req, res) {
Book.findOne({isbn: req.params.isbn}, function (err, book){
if ((err) || (!book)) {
res.send(422,'delete failed');
} else {
book.remove(function(err){
if (err) {
res.send(422,'delete failed');
} else {
res.send(200,'OK');
}
})
}
});
});
});
module.exports = app