-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
104 lines (79 loc) · 2 KB
/
server.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
var express = require('express');
var app = express();
var seed = 0;
var users = {
0 : {
name : "Geronimo Garcia Sgritta",
age : 27,
superpower : "Nerdines"
}
};
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
// intercept OPTIONS method
if ('OPTIONS' == req.method) {
res.send(200);
}
else {
next();
}
};
app.configure(function () {
app.use(express.bodyParser());
app.use(allowCrossDomain);
app.use(app.router);
app.use(express.static(__dirname));
});
app.get('/user', function(req, res){
res.json(200, users);
});
app.post('/user', function(req, res){
var
id = ++seed,
user = {
name : req.param('name'),
age : req.param('age'),
superpower : req.param('superpower')
};
users[id] = user;
user.id = id;
res.json(200, { "success" : true, "data" : user});
});
app.get('/user/:id', function(req, res){
var id = req.params.id,
user = { };
user[id] = users[id];
if(! user){
user = { found : false};
user.id = id;
}
res.json(200, user);
});
app.put('/user/:id', function(req, res){
var id = req.params.id,
user;
if(! id in users){
return res.json(404, { id: id, found : false });
}
user = users[id];
user.name = req.body.name;
user.age = req.body.age;
user.superpower = req.body.superpower;
users[id] = user;
user.id = id;
res.json(200, { "success" : true, "data" : user});
});
app.delete('/user/:id', function(req, res){
var
id = req.params.id,
found = false;
if(id in users){
delete users[id];
found = true;
}
res.json(200, { "deleted" : ""+found });
});
app.listen(3000);
console.log("App listening in port 3000");