-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
92 lines (80 loc) · 2.26 KB
/
index.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
var express = require('express'),
campus = require('./campus'),
path = require('path'),
async = require('async');
var app = express();
var roomCache = {},
campusConfigs = {
216: {
id:'pcv',
name:'Peter Cooper Village'
},
219: {
id:'st',
name:'Stuyvesant Town'
}
};
function setUpRoutes() {
app.get('/rooms', function(req, res) {
return res.send(roomCache);
});
app.get('/room/:roomId', function(req, res) {
var room = roomCache[req.params.roomId],
roomIsValid = false;
if (room !== undefined) {
var cacheRefreshDue = new Date(room.nextRefreshDue);
if (cacheRefreshDue > new Date()) {
roomIsValid = true;
}
} else {
return res.send(404, "Room " + req.params.roomId + " does not exist");
}
if (roomIsValid) {
res.send(room);
} else {
room.loadRoom(function(error, room) {
if (error) {
return res.send(500, {
error: error
});
} else {
roomCache[room.roomId] = room;
return res.send(room);
}
});
}
});
console.log("Initialized routes");
}
function loadRoomCache() {
var loadFunctions = {};
for (var campusId in campusConfigs) {
var campusConfig = campusConfigs[campusId];
var c = new campus.Campus(campusId, campusConfig.name);
campusConfig['campus'] = c;
loadFunctions[campusId] = c.loadRooms.bind(c);
}
async.parallel(loadFunctions, function(err, results) {
if (err) {
console.log("Error getting rooms lists: ", err);
} else {
for (var campusId in results) {
var campusRooms = results[campusId];
for (var roomId in campusRooms) {
roomCache[roomId] = campusRooms[roomId];
}
}
console.log('Loaded ' + Object.keys(roomCache).length + ' rooms across ' + Object.keys(results).length + ' campuses');
setUpRoutes();
}
});
};
app.configure(function() {
loadRoomCache();
app.use(app.router);
app.use(express.static(path.join(__dirname, "web"), {maxAge: 31557600000}));
});
var port = process.env.PORT || process.env.VCAP_APP_PORT || 1337;
var server = app.listen(port, function() {
console.log('Server started on port %d', server.address().port);
})