forked from bargenson/Express-TodoList-Server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
74 lines (63 loc) · 1.57 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
var express = require('express'),
todoAdapter = require('./todo_adapter').todoAdapter,
Todo = require('./todo').Todo;
var app = express();
addMiddlewares();
app.options("*", function(req, res) {
res.header('Allow', 'GET,POST,OPTIONS');
res.send(200);
});
app.get('/todos', function(req, res){
todoAdapter.getTodos(function(err, result) {
if(err) {
res.send(500, err.message);
} else {
res.json({ todos: result });
}
});
});
app.post('/todos', function(req, res){
todoAdapter.addTodo(
new Todo(
req.body.title,
req.body.description,
req.body.deadLine
), function(err, index) {
if(err) {
res.send(400, err.message);
} else {
res.set('Location', '/todos/' + index);
res.send(201, JSON.stringify({ todoId: index }));
}
}
);
});
app.get('/todos/:id', function(req, res){
var todoId = req.params.id;
todoAdapter.getTodo(req.params.id, function(err, result) {
if(err) {
res.send(500, err.message);
} else if(result) {
res.json(result);
} else {
res.send(404, "The todo with ID=" + todoId + " doesn't exist.");
}
});
});
startListen();
function startListen() {
var port = process.env.PORT || 3000;
app.listen(port, function() {
console.log('Listening on port 3000');
});
}
function addMiddlewares() {
app.use(express.bodyParser());
app.use(addCorsHeaders);
}
function addCorsHeaders(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type,X-Requested-With');
next();
}