-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
72 lines (56 loc) · 2.05 KB
/
app.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
var path = require("path"),
strata = require("strata"),
redirect = strata.redirect;
strata.use(strata.commonLogger);
strata.use(strata.contentType, "text/html");
strata.use(strata.file, path.join(__dirname, "public"), "index.html");
strata.use(strata.jsonp);
// An array of messages that have been posted to this chat. Each message is
// stored as an object with three properties: time, user, and text.
var history = [];
// The number of events to keep around in the chat history.
var MAX_HISTORY_LENGTH = 10000;
// GET /messages-create?user=:user&text=:text
strata.get("/messages-create", function (env, callback) {
var req = strata.Request(env);
req.params(function (err, params) {
var user = params.user;
var text = params.text;
if (user && text) {
// Add the message to the chat history.
history.push({
time: (new Date).getTime(),
user: user,
text: text
});
// Keep the # of items in the history under MAX_HISTORY_LENGTH.
while (history.length > MAX_HISTORY_LENGTH) {
history.shift();
}
var content = JSON.stringify({ message: "You have successfully added a new message to the chat." });
callback(201, {"Content-Type": "application/json"}, content);
} else {
var content = JSON.stringify({ message: "You must provide both a user and a message." });
callback(400, {"Content-Type": "application/json"}, content);
}
});
});
// GET /messages?since=:milliseconds
strata.get("/messages", function (env, callback) {
var req = strata.Request(env);
req.params(function (err, params) {
var since = parseInt(params.since),
messages;
if (isNaN(since)) {
// If no "since" was given, just return the last 100 messages.
messages = history.slice(-100);
} else {
messages = history.filter(function (message) {
return message.time > since;
});
}
var content = JSON.stringify({ messages: messages });
callback(200, {"Content-Type": "application/json"}, content);
});
});
module.exports = strata.app;