Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
110 lines (88 loc) · 2.25 KB
/
Copy pathserver.js
File metadata and controls
110 lines (88 loc) · 2.25 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
var express = require('express');
var bodyParser = require('body-parser');
var _ = require('underscore');
var app = express();
var PORT = process.env.PORT || 3000;
var todos = [];
var todoNextID = 1;
app.use(bodyParser.json());
app.get('/',
function(req, res) {
res.send('Todo API Root');
}
);
// GET /todos
app.get('/todos',
function(req, res) {
res.json(todos);
}
);
// GET /todos/:id
app.get('/todos/:id',
function(req, res) {
var todoID = parseInt(req.params.id, 10);
var matchedTodo = _.findWhere(todos, {id: todoID});
if (matchedTodo) {
res.json(matchedTodo);
} else {
res.status(404).send();
}
}
);
// POST /todos
app.post('/todos',
function(req, res) {
var body = _.pick(req.body, "description", "completed");
if (!_.isBoolean(body.completed) || !_.isString(body.description)
|| body.description.trim().length ==- 0) {
return res.status(400).send();
}
body.description = body.description.trim();
body.id = todoNextID++;
todos.push(body);
res.json(body);
}
);
// DELETE /todos/:id
app.delete('/todos/:id',
function(req, res) {
var todoID = parseInt(req.params.id, 10);
var matchedTodo = _.findWhere(todos, {id: todoID});
if (matchedTodo) {
todos = _.without(todos, matchedTodo);
res.status(200).json(matchedTodo);
} else {
res.status(404).send();
}
}
);
// PUT
app.put('/todos/:id',
function(req, res) {
var todoID = parseInt(req.params.id, 10);
var matchedTodo = _.findWhere(todos, {id: todoID});
if (!matchedTodo) {
return res.status(404).send();
}
var body = _.pick(req.body, "description", "completed");
var validatedAttributes = {};
if (body.hasOwnProperty("completed") && _.isBoolean(body.completed)) {
validatedAttributes.completed = body.completed;
} else if (body.hasOwnProperty("completed")) {
return res.status(400).send();
}
if (body.hasOwnProperty("description") && _.isString(body.description)
&& body.description.trim().length > 0) {
validatedAttributes.description = body.description;
} else if (body.hasOwnProperty("description")) {
return res.status(400).send();
}
_.extend(matchedTodo, validatedAttributes);
res.json(matchedTodo);
}
);
app.listen(PORT,
function() {
console.log("Express listening on port " + PORT + "!");
}
);