-
Notifications
You must be signed in to change notification settings - Fork 2
/
skillShareServer.js
171 lines (149 loc) · 4.23 KB
/
skillShareServer.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
const {createServer} = require('http');
const Router = require('./router');
const ecstatic = require('ecstatic');
const router = new Router();
const defaultHeaders = {"Content-Type": "text/plain"};
class SkillShareServer {
constructor(talks) {
this.talks = talks;
this.version = 0;
this.waiting = [];
let fileServer = ecstatic({root: "./public"});
this.server = createServer((request, response) => {
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);
}
});
}
start(port) {
this.server.listen(port);
}
stop() {
this.server.close();
}
}
const talkPath = /^\/talks\/([^\/]+)$/;
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`};
}
});
router.add('DELETE', talkPath, async (server, title) => {
if (title in server.talks) {
delete server.talks[title];
server.updated();
}
return {status: 204};
});
function readStream (stream) {
return new Promise((resolve, reject) => {
let data = '';
stream.on('error', reject);
stream.on('data', chunk => data += chunk.toString());
stream.on('end', () => resolve(data));
});
}
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};
});
router.add("POST", /^\/talks\/([^\/]+)\/comments$/,
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: 400, 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`};
}
});
SkillShareServer.prototype.talkResponse = function () {
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}"`}
};
};
router.add('GET', /^\/talks$/, 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]));
}
});
SkillShareServer.prototype.waitForChanges = function(time) {
return new Promise(resolve => {
this.waiting.push(resolve);
setTimeout(() => {
if (!this.waiting.includes(resolve)) return;
this.waiting = this.waiting.filter(r => r != resolve);
resolve({status: 304});
}, time * 1000);
});
};
const {readFileSync, writeFile} = require('fs');
const filePath = './talks.json';
SkillShareServer.prototype.updated = function() {
this.version++;
let response = this.talkResponse();
this.waiting.forEach(resolve => resolve(response));
this.waiting = [];
writeFile(filePath, JSON.stringify(this.talks), (error) => {
if (error) throw error;
console.log('The file has been saved.')
});
};
function loadTalks () {
let json;
try{
json = JSON.parse(readFileSync(filePath,'utf8'));
} catch (e) {
json = {};
}
return Object.assign(Object.create(null),json);
}
new SkillShareServer(loadTalks()).start(8000);