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
|
// get the todos collection
var todoCollect = require('./models/todo');
// use mongo to get all the items in db
function getTodos (res) {
todoCollect.find(function (err, todos) {
if (err) res.send(err);
res.json(todos); // return all todos in JSON format
// console.log(todos);
});
}
// ===========================API===============================
module.exports = function (app) {
// get all items
app.get('/api/todos', function (req, res) {
getTodos(res);
});
// create an item
app.post('/api/todos', function (req, res) {
// add item to the list
todoCollect.create({
text: req.body.text,
done: false
}, function (err, todo) {
if (err) res.send(err);
// 'refresh' to-do list
getTodos(res);
});
});
// delete item
app.delete('/api/todos/:todo_id', function (req, res) {
todoCollect.remove({
_id: req.params.todo_id
}, function (err, todo) {
if (err) res.send(err);
// 'refresh' to-do list
getTodos(res);
});
});
// load the static html file for now
app.get('*', function (req, res) {
res.sendFile(__dirname + '/public/index.html');
});
};
|