forked from clarissalittler/backbone-tutorials
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathmulti-server.js
79 lines (64 loc) · 1.83 KB
/
multi-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
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended : false}));
app.use(express.static(__dirname));
var database = {};
database.users = [
{id:0, username:'Dan'},
{id:1, username:'Tom'},
{id:2, username:'Shackleton'}
];
database.issues = [
{id:0, title:'Do some work', description:'Finish all the things', creator:'Dan'},
{id:1, title:'go kat fud stor', description:'', creator:'Shackleton'},
{id:2, title:'ticl dog', description:'deserv itt', creator:'Shackleton', status:'claimed', assignee:'Shackleton'}
];
function showData(collname) {
console.log(collname+' data store is now: ', database[collname]);
}
function getOne(collname) {
app.get('/'+collname+'/:id', function (req, res) {
var id = req.params.id;
console.log('Sending model #%s...',id);
res.send(database[collname][id]);
});
}
function putOne(collname) {
app.put('/'+collname+'/:id', function (req, res) {
var id = req.params.id;
console.log('Receiving model #%s...',id);
database[collname][id] = req.body;
showData(collname);
res.send({});
});
}
function postOne(collname) {
app.post('/'+collname, function (req, res) {
console.log('Receiving new model...');
var newid = database[collname].length;
console.log('Assigning id of %s',newid);
var obj = req.body;
obj.id = newid;
database[collname][newid] = obj;
showData(collname);
res.send(obj);
});
}
function getAll(collname) {
app.get('/'+collname, function (req, res) {
console.log('Sending all models...');
showData(collname);
res.send(database[collname]);
});
}
function makeRoutes(collname) {
getOne(collname);
postOne(collname);
putOne(collname);
getAll(collname);
}
Object.keys(database).forEach(makeRoutes);
app.listen(3000);
Object.keys(database).forEach(showData);