-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
106 lines (93 loc) · 2.7 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
105
106
var express = require('express'),
app = express(),
request = require('request'),
_ = require('underscore'),
githubauth = require('./githubauth');
// Keep an array of messages
var msgs = [];
// Serve index.html as static text
app.use(express.static(__dirname + '/public'));
// Convenience for allowing CORS on routes - GET and POST
app.use(function(req, res, next) {
var oneof;
oneof = false;
if (req.headers.origin) {
res.header("Access-Control-Allow-Origin", req.headers.origin);
oneof = true;
}
if (req.headers["access-control-request-method"]) {
res.header("Access-Control-Allow-Methods", req.headers["access-control-request-method"]);
oneof = true;
}
if (req.headers["access-control-request-headers"]) {
res.header("Access-Control-Allow-Headers", req.headers["access-control-request-headers"]);
oneof = true;
}
if (oneof) {
res.header("Access-Control-Max-Age", 60 * 60 * 24 * 365);
}
if (oneof && req.method === "OPTIONS") {
return res.send(200);
} else {
return next();
}
});
app.use(express.urlencoded());
function createResponse(newMsgs) {
var refreshSince = new Date();
if (newMsgs.length > 0) {
refreshSince = newMsgs[newMsgs.length-1].timestamp;
}
return {
msgs: newMsgs,
refreshSince: refreshSince
};
}
githubauth(app);
app.get('/msgs/:since?', function(req, res) {
if (!req.params.since) {
res.json(createResponse(msgs));
} else {
var since = new Date(req.params.since);
var recentMsgs = [];
console.log('asking since:');
console.log(since);
console.log('actual most recent:');
if (msgs.length > 0) {
console.log(msgs[msgs.length-1].timestamp);
}
msgs.forEach(function(msg) {
if (msg.timestamp > since) {
recentMsgs.push(msg);
}
});
res.json(createResponse(recentMsgs));
}
});
app.post('/msgs', function(req, res) {
var msg = req.body;
console.log (msg);
msg.timestamp = new Date();
msgs.push(msg);
res.send("OK");
});
app.get('/styles', function(req, res) {
request.get('http://api.plnkr.co/tags/byocstyle', function (error, response, body) {
if (!error && response.statusCode == 200) {
body = JSON.parse(body);
var userStyles = _.map(body, function(item) {
var url = item.url;
return {
user: item.user.login,
name: item.description,
id: item.id
}
});
res.json(userStyles);
}
});
});
var port = process.env.PORT || 80;
app.listen(port, null, function (err) {
console.log('Your chat server is listening at: http://localhost:' + port);
});