-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
89 lines (75 loc) · 2.6 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
var restify = require('restify');
// State
var next_user_id = 0;
var users = {};
// Server
var server = restify.createServer({
name: 'awkwardGit',
version: '1.0.0'
});
server.use(restify.acceptParser(server.acceptable));
server.use(restify.queryParser());
server.use(restify.bodyParser());
server.get("/", function (req, res, next) {
res.writeHead(200, {'Content-Type': 'application/json; charset=utf-8'});
res.end(JSON.stringify(users));
return next();
});
server.get('/user/:id', function (req, res, next) {
res.writeHead(200, {'Content-Type': 'application/json; charset=utf-8'});
res.end(JSON.stringify(users[parseInt(req.params.id)]));
return next();
});
server.post('/user', function (req, res, next) {
var user = req.params;
user.id = next_user_id++;
users[user.id] = user;
res.writeHead(200, {'Content-Type': 'application/json; charset=utf-8'});
res.end(JSON.stringify(user));
return next();
});
server.put('/user/:id', function (req, res, next) {
var user = users[parseInt(req.params.id)];
var changes = req.params;
delete changes.id;
for(var x in changes) {
user[x] = changes[x];
}
res.writeHead(200, {'Content-Type': 'application/json; charset=utf-8'});
res.end(JSON.stringify(user));
return next();
});
server.del('/user/:id', function (req, res, next) {
delete users[parseInt(req.params.id)];
res.writeHead(200, {'Content-Type': 'application/json; charset=utf-8'});
res.end(JSON.stringify(true));
return next();
});
server.listen(18081, function () {
console.log('%s listening at %s', server.name, server.url);
});
// Client
var client = restify.createJsonClient({
url: 'http://localhost:18081',
version: '~1.0'
});
client.post('/user', { name: "John Doe" }, function (err, req, res, obj) {
if(err) console.log("An error ocurred:", err);
else console.log('POST /user returned: %j', obj);
client.get('/user/0', function (err, req, res, obj) {
if(err) console.log("An error ocurred:", err);
else console.log('GET /user/0 returned: %j', obj);
client.put('/user/0', { country: "USA" }, function (err, req, res, obj) {
if(err) console.log("An error ocurred:", err);
else console.log('PUT /user/0 returned: %j', obj);
client.del('/user/0', function (err, req, res, obj) {
if(err) console.log("An error ocurred:", err);
else console.log('DELETE /user/0 returned: %j', obj);
client.get('/', function (err, req, res, obj) {
if(err) console.log("An error ocurred:", err);
else console.log('GET / returned: %j', obj);
});
});
});
});
});