-
Notifications
You must be signed in to change notification settings - Fork 0
/
talks_board_server.js
333 lines (301 loc) · 8.71 KB
/
talks_board_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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
const {createServer} = require("http");
const Router = require("./router");
const ecstatic = require("ecstatic");
const {writeFile} = require("mz/fs");
const {readFileSync} = require("fs");
const router = new Router();
const defaultHeaders = {"Content-Type": "text/plain"};
// A regex which handles the 'talks' route with a title.
// This can be used to add, delete or retrieve a talk.
const talkPath = /^\/talks\/([^\/]+)$/;
// A regex which handles the 'talks' route with a comment.
// This can be used to add comments.
const talkPathAddComment = /^\/talks\/([^\/]+)\/comments$/;
// A regex which handles the talks route without any
// further path elements.
const talksPath = /^\/talks$/;
/**
* A server which routes all 'unknown' routes
* to a static fileserver ('ecstatic') but has the
* ability to route 'known' routes to a custom handler.
*
* @class SkillShareServer
*/
class SkillShareServer {
/**
* Creates an instance of SkillShareServer.
*
* @param {object} talks An object without a prototype.
* @memberof SkillShareServer
*/
constructor(talks) {
this.talks = talks;
/**
* The version of the talks objects.
* @type {number}
*/
this.version = 0;
/**
* An array of open requests (long polling).
* @type {array}
*/
this.waiting = [];
let fileServer = ecstatic({root: "./public"});
this.server = createServer((request, response) => {
console.log("request.url: ", request.url);
let resolved = router.resolve(this, request);
if(resolved) {
resolved
.catch(error => {
if(error.status != null) return error;
return {body: String(error), status: 500};
})
.then(({ body,
status = 200,
headers = defaultHeaders}) => {
response.writeHead(status, headers);
response.end(body);
});
}
else {
fileServer(request, response);
}
});
}
/**
* Starts the server.
* @param {number} port The port this server listens to.
* @memberof SkillShareServer
*/
start(port) {
this.loadTalks();
this.server.listen(port);
}
/**
* Stops this server.
* @memberof SkillShareServer
*/
stop() {
this.server.close();
}
/**
* Helper method.
* @returns {object} Object containing data for the respons of
* a request to the talks url.
* @memberof SkillShareServer
*/
talkResponse() {
let talks = [];
for(let title of Object.keys(this.talks)) {
talks.push(this.talks[title]);
}
return {
body: JSON.stringify(talks),
headers: {
"Content-Type" : "application/json",
"ETag" : `"${this.version}"`
}
}
}
/**
* @param {number} time Waiting time in milliseconds
* @returns {object} A Promise which resolves after a certain time.
* @memberof SkillShareServer
*/
waitForChanges(time) {
return new Promise((resolve) => {
this.waiting.push(resolve);
setTimeout(() => {
// The 'wait-time' is over for the reuqest in
// question.
// In case the promise has been resolved already.
// This can happen if 'updated()' has been triggered.
if(!this.waiting.includes(resolve)) return;
// The waiting response will be triggered now, the
// element can be removed.
this.waiting = this.waiting.filter(elem => elem != resolve);
// Nothing has changed. Therefore no new talks have to be
// returned.
return {
status: 304
};
}, time * 1000);
});
}
/**
* A change has been made to the talks object.
* @memberof SkillShareServer
*/
updated() {
this.version++;
let response = this.talkResponse();
this.waiting.forEach(resolve => resolve(response));
this.waiting = [];
this.writeTalks();
}
/**
* Loads talks data from disc.
* @memberof SkillShareServer
*/
loadTalks() {
try {
let jsonTalks = readFileSync("./talks.json", "utf8");
// This is an object with a prototype.
let obj = JSON.parse(jsonTalks);
// The talks object must be an object without a prototype.
this.talks = Object.assign(Object.create(null), obj);
}
catch(error) {
if(error instanceof SyntaxError){
console.log(`Bad talks data in file ${"talks.json"}, ${error.toString()}`);
}
else if(error.code != "ENOENT"){
throw error;
}
}
}
/**
* Writes talks data to disc.
* @memberof SkillShareServer
*/
writeTalks() {
writeFile("./talks.json", JSON.stringify(this.talks), "utf8")
.then(() => {
console.log("writeTalks: ", "Talks successfulle written to disc.");
})
.catch((error) => {
console.log("writeTalks: ", "Error: ", error);
});
}
}
// Adds the route to retrieve a talk.
router.add("GET", talkPath, async (server, title) => {
if(title in server.talks) {
return {
body: JSON.stringify(server.talks[title]),
headers: {"Content-Type": "application/json"}
};
}
else {
return {
status: 404,
body: `No talk '${title}' found`
};
}
});
// Adds a route to delete a talk.
router.add("DELETE", talkPath, async (server, title) => {
if(title in server.talks) {
delete server.talks[title];
server.updated();
}
return {status: 204};
});
/**
* Helper function to retrieve the content of a request body.
*
* @param {object} stream A stream.
*/
function readStream(stream) {
return new Promise((resolve, reject) => {
let data = "";
stream.on("error", (error) => {
console.log("readStream error", error);
reject(error);
});
stream.on("data", chunk => {
console.log("readStream data", data);
data += chunk.toString()
});
stream.on("end", () => {
console.log("readStream end", data);
resolve(data)
});
});
}
// Adds a route to add a talk.
router.add("PUT", talkPath, async (server, title, request) => {
let requestBody = await readStream(request);
let talk;
try {
talk = JSON.parse(requestBody);
}
catch(_) {
return {
status: 400,
body: "Invalid JSON"
};
}
if(!talk ||
typeof talk.presenter != "string" ||
typeof talk.summary != "string") {
return {
status: 400,
body: "Bad talk data"
};
}
server.talks[title] = {
title,
presenter: talk.presenter,
summary: talk.summary,
comments: []
};
server.updated();
return {
status: 204
};
});
// Adds a comment to a talk.
router.add("POST", talkPathAddComment,
async (server, title, request) => {
let requestBody = await readStream(request);
let comment;
try {
comment = JSON.parse(requestBody);
}
catch(_){
return {
status: 400,
body: "Invalid JSON"
};
}
if(!comment ||
typeof comment.author != "string" ||
typeof comment.message != "string") {
return {
status: 404,
body: "Bad comment data"
};
}
else if(title in server.talks) {
server.talks[title].comments.push(comment);
server.updated();
return {
status: 204
};
}
else {
return {
status: 404,
body: `No talk '${title}' found`
};
}
});
// Adds a route to retrieve all talks.
router.add("GET", talksPath, async (server, request) => {
let tag = /"(.*)"/.exec(request.headers["if-none-match"]);
let wait = /\bwait=(\d+)/.exec(request.headers["prefer"]);
if(!tag || tag[1] != server.version) {
return server.talkResponse();
}
else if(!wait){
return {
status: 304
};
}
else {
return server.waitForChanges(Number(wait[1]));
}
});
let server = new SkillShareServer(Object.create(null));
server.start(8000);