-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrest.js
49 lines (46 loc) · 1.42 KB
/
rest.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
var http = require('http');
var url = require('url');
var items = [];
http.createServer(function(req, res) {
console.log(req.method);
switch (req.method) {
case 'POST':
//curl http://localhost:8000 -d "elemento nuevo"
var item = '';
req.setEncoding('utf8');
req.on('data', function(chunk){
console.log(chunk);
item += chunk;
});
req.on('end', function(){
items.push(item);
res.end('OK\n');
});
break;
case 'GET':
//curl http://localhost:8000
items.forEach(function(item, i){
res.write(i + ') ' + item + '\n');
});
res.end();
break;
case 'DELETE':
//curl http://localhost:8000/1 -X DELETE
console.log('borando');
var path = url.parse(req.url).pathname;
console.log(path);
var i = parseInt(path.slice(1), 10);
console.log(i);
if (isNaN(i)) {
res.statusCode = 400;
res.end('Invalid item id');
} else if (!items[i]) {
res.statusCode = 404;
res.end('Item not found');
} else {
items.splice(i, 1);
res.end('OK\n');
}
break;
}
}).listen(8000, "127.0.0.1");