-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcontroller.js
83 lines (73 loc) · 1.98 KB
/
controller.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
var Todo = require('./todo.js').Todo;
var addUrl = function(server, todo){
var baseUrl = 'http://' + server.host;
todo.url = baseUrl + '/' + todo._id;
return todo;
}
var save = function(request, reply){
todo = new Todo();
todo.title = request.payload.title;
todo.order = request.payload.order;
todo.save(function (err) {
if (!err) {
var response = addUrl(request.info, todo);
reply(response);
} else {
reply(Hapi.error.internal('Internal MongoDB error', err));
}
});
};
var update = function(request, reply){
Todo.findOneAndUpdate(request.params.id, request.payload, function (err, todo) {
if (!err) {
var response = addUrl(request.info, todo);
reply(response);
} else {
reply(Hapi.error.internal('Internal MongoDB error', err));
}
});
};
var getAll = function(request, reply){
var todosWithUrl = [];
Todo.find({}, function (err, todos) {
if (!err) {
for(i in todos){
todosWithUrl.push(addUrl(request.info, todos[i]));
}
reply(todosWithUrl);
} else {
reply(err);
}
});
};
var getById = function(request, reply){
Todo.findById(request.params.id, function(err, todo){
if (err){
reply(err);
}
var response = addUrl(request.info, todo);
reply(response);
});
};
var deleteAll = function(request, reply) {
Todo.remove({}, function (err, todos) {
if (err) return reply(Hapi.error.internal('Internal MongoDB error', err));
return reply("Deleted all todos");
});
};
var deleteById = function(request, reply) {
Todo.findById(request.params.id, function (err, todo){
if (err) return reply(Hapi.error.internal('Internal MongoDB error', err));
todo.remove();
reply("Record Deleted");
});
};
var controller = {
save: save,
update: update,
getAll: getAll,
deleteAll: deleteAll,
getById: getById,
deleteById: deleteById,
}
module.exports = controller;