This repository was archived by the owner on May 12, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathchat_server_with_objects.js
More file actions
75 lines (64 loc) · 2.02 KB
/
chat_server_with_objects.js
File metadata and controls
75 lines (64 loc) · 2.02 KB
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
const http = require('http');
const Assistant = require('./lib/assistant');
const House = require('./lib/house')
const port = process.env.PORT || 5000;
let chatHouse = new House();
http.createServer(handleRequest).listen(port);
console.log("Listening on port " + port);
function handleRequest(request, response) {
// let url = new URL(request.url, 'http://localhost:5000/')
let url = require('url').parse(request.url);
let path = url.pathname;
console.log('Finding ' + path);
let assistant = new Assistant(request, response);
// "routing" happens here (not very complicated)
let pathParams = parsePath(path);
if (isChatAction(pathParams)) {
handleChatAction(request, assistant);
}
else if (assistant.isRootPathRequested()) {
assistant.sendFile('./public/chat.html');
}
else {
assistant.handleFileRequest();
}
}
function parsePath(path) {
let format;
if (path.endsWith('.json')) {
path = path.substring(0, path.length - 5);
format = 'json';
}
let pathParts = path.slice(1).split('/');
let action = pathParts.shift();
let id = pathParts.shift();
let pathParams = { action: action, id: id, format: format };
return pathParams;
}
function isChatAction(pathParams) {
return (pathParams.action === 'chat');
}
function handleChatAction(request, handler) {
if (request.method === 'GET') {
sendChatMessages(handler);
} else if (request.method === 'POST') {
handler.parsePostParams((params) => {
let messageOptions = {
author: params.author,
body: params.body
}
chatHouse.sendMessageToRoom('general', messageOptions);
sendChatMessages(handler);
});
} else {
handler.sendError(405, "Method '" + request.method + "' Not Allowed");
}
}
function sendChatMessages(handler) {
let oneHour = (1000 * 60 * 60);
let since = new Date(Date.now() - oneHour);
let messages = chatHouse.roomWithId('general').messagesSince(since);
let data = JSON.stringify(messages);
let contentType = 'text/json';
handler.finishResponse(contentType, data);
}