-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
485 lines (427 loc) · 13.5 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
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
const yaml = require('js-yaml');
const toyaml = require('write-yaml');
const fs = require('fs');
const dbFile = fs.readFileSync('./src/utils/database.yaml');
function loadDatabase() {
return yaml.safeLoad(dbFile);
}
function saveDatabase(data) {
toyaml('./src/utils/database.yaml', data, function(e){
console.log(e);
})
}
const database = loadDatabase();
const routes = {
'/users': {
'POST': getOrCreateUser
},
'/users/:username': {
'GET': getUser
},
'/comments': {
'POST': createComment
},
'/comments/:id': {
'PUT': updateComment,
'DELETE': deleteComment
},
'/comments/:id/upvote': {
'PUT': upvoteComment
},
'/comments/:id/downvote': {
'PUT': downvoteComment
},
'/articles': {
'GET': getArticles,
'POST': createArticle
},
'/articles/:id': {
'GET': getArticle,
'PUT': updateArticle,
'DELETE': deleteArticle
},
'/articles/:id/upvote': {
'PUT': upvoteArticle
},
'/articles/:id/downvote': {
'PUT': downvoteArticle
}
};
function getUser(url, request) {
const username = url.split('/').filter(segment => segment)[1];
const user = database.users[username];
const response = {};
if (user) {
const userArticles = user.articleIds.map(
articleId => database.articles[articleId]);
const userComments = user.commentIds.map(
commentId => database.comments[commentId]);
response.body = {
user: user,
userArticles: userArticles,
userComments: userComments
};
response.status = 200;
} else if (username) {
response.status = 404;
} else {
response.status = 400;
}
return response;
}
function getOrCreateUser(url, request) {
const username = request.body && request.body.username;
const response = {};
if (database.users[username]) {
response.body = {user: database.users[username]};
response.status = 200;
} else if (username) {
const user = {
username: username,
articleIds: [],
commentIds: []
};
database.users[username] = user;
response.body = {user: user};
response.status = 201;
} else {
response.status = 400;
}
saveDatabase(database);
return response;
}
function createComment(url, request) {
const body = request.body && request.body.comment;
const {comments, users, articles} = database;
const response = {};
if (body) {
const {body : b, articleId, username} = body;
const user = users[username];
const article = articles[articleId];
if (articleId && username && user && article && b) {
const comment = {
id: database.nextCommentId++,
body: b,
username: username,
articleId: articleId,
upvotedBy: [],
downvotedBy: []
};
comments[comment.id] = comment;
user.commentIds.push(comment.id);
article.commentIds.push(comment.id);
response.body = {comment: comment};
response.status = 201;
} else {
response.status = 400;
}
} else {
response.status = 400;
}
saveDatabase(database);
return response;
}
function updateComment(url, request) {
const id = Number(url.split('/').filter(segment => segment)[1]);
const body = request.body && request.body.comment;
const {comments} = database;
const savedComment = comments[id];
const response = {};
if (!id || !body) {
response.status = 400;
} else if (!savedComment) {
response.status = 404;
} else {
const {body : b} = body;
savedComment.body = b || savedComment.body;
response.body = {comment: savedComment};
response.status = 200;
}
saveDatabase(database);
return response;
}
function deleteComment(url, request) {
const id = Number(url.split('/').filter(segment => segment)[1]);
const {users, comments, articles} = database;
const savedComment = comments[id];
const response = {}
if (savedComment) {
const userCommentId = users[savedComment.username].commentIds;
const articleCommentId = articles[savedComment.articleId].commentIds;
userCommentId.indexOf(id) < 0 ? null : userCommentId.splice(userCommentId.indexOf(id), 1);
articleCommentId.indexOf(id) < 0 ? null : articleCommentId.splice(articleCommentId.indexOf(id), 1);
comments[id] = null;
// makes a test fail
// delete comments[id];
response.status = 204;
} else {
response.status = 404;
}
saveDatabase(database);
return response;
}
function upvoteComment(url, request) {
const id = Number(url.split('/').filter(segment => segment)[1]);
const username = request.body && request.body.username;
const {users, comments} = database;
let savedComment = comments[id];
const response = {};
if (id && username && savedComment && users[username]) {
const userHasUpvoted = savedComment.upvotedBy.indexOf(username);
const userHasDownvoted = savedComment.downvotedBy.indexOf(username);
if (userHasDownvoted > -1) {
savedComment.downvotedBy.splice(userHasDownvoted, 1);
savedComment = upvote(savedComment, username);
} else if (userHasUpvoted < 0) {
savedComment = upvote(savedComment, username);
}
response.body = {comment: savedComment};
response.status = 200;
} else if (!savedComment){
response.body = {message: `Comment with id of ${id} not found.`}
response.status = 400; // should be 404 response status
} else {
response.status = 400;
}
saveDatabase(database);
return response;
}
function downvoteComment(url, request) {
const id = Number(url.split('/').filter(segment => segment)[1]);
const username = request.body && request.body.username;
const {users, comments} = database;
let savedComment = comments[id];
const response = {};
if (id && savedComment && username && users[username]) {
const userHasUpvoted = savedComment.upvotedBy.indexOf(username);
const userHasDownvoted = savedComment.downvotedBy.indexOf(username);
if (userHasUpvoted > -1) {
savedComment.upvotedBy.splice(userHasUpvoted,1);
savedComment = downvote(savedComment, username);
} else if (userHasDownvoted < 0) {
savedComment = downvote(savedComment, username);
}
response.body = {comment: savedComment};
response.status = 200;
} else if (!savedComment){
response.body = {message: `Comment with id of ${id} not found.`}
response.status = 400; // should be 404 response status
} else {
response.status = 400;
}
saveDatabase(database);
return response;
}
function getArticles(url, request) {
const response = {};
response.status = 200;
response.body = {
articles: Object.keys(database.articles)
.map(articleId => database.articles[articleId])
.filter(article => article)
.sort((article1, article2) => article2.id - article1.id)
};
saveDatabase(database);
return response;
}
function getArticle(url, request) {
const id = Number(url.split('/').filter(segment => segment)[1]);
const article = database.articles[id];
const response = {};
if (article) {
article.comments = article.commentIds.map(
commentId => database.comments[commentId]);
response.body = {article: article};
response.status = 200;
} else if (id) {
response.status = 404;
} else {
response.status = 400;
}
saveDatabase(database);
return response;
}
function createArticle(url, request) {
const requestArticle = request.body && request.body.article;
const response = {};
if (requestArticle && requestArticle.title && requestArticle.url &&
requestArticle.username && database.users[requestArticle.username]) {
const article = {
id: database.nextArticleId++,
title: requestArticle.title,
url: requestArticle.url,
username: requestArticle.username,
commentIds: [],
upvotedBy: [],
downvotedBy: []
};
database.articles[article.id] = article;
database.users[article.username].articleIds.push(article.id);
response.body = {article: article};
response.status = 201;
} else {
response.status = 400;
}
saveDatabase(database);
return response;
}
function updateArticle(url, request) {
const id = Number(url.split('/').filter(segment => segment)[1]);
const savedArticle = database.articles[id];
const requestArticle = request.body && request.body.article;
const response = {};
if (!id || !requestArticle) {
response.status = 400;
} else if (!savedArticle) {
response.status = 404;
} else {
savedArticle.title = requestArticle.title || savedArticle.title;
savedArticle.url = requestArticle.url || savedArticle.url;
response.body = {article: savedArticle};
response.status = 200;
}
saveDatabase(database);
return response;
}
function deleteArticle(url, request) {
const id = Number(url.split('/').filter(segment => segment)[1]);
const savedArticle = database.articles[id];
const response = {};
if (savedArticle) {
database.articles[id] = null;
savedArticle.commentIds.forEach(commentId => {
const comment = database.comments[commentId];
database.comments[commentId] = null;
const userCommentIds = database.users[comment.username].commentIds;
userCommentIds.splice(userCommentIds.indexOf(id), 1);
});
const userArticleIds = database.users[savedArticle.username].articleIds;
userArticleIds.splice(userArticleIds.indexOf(id), 1);
response.status = 204;
} else {
response.status = 400;
}
saveDatabase(database);
return response;
}
function upvoteArticle(url, request) {
const id = Number(url.split('/').filter(segment => segment)[1]);
const username = request.body && request.body.username;
let savedArticle = database.articles[id];
const response = {};
if (savedArticle && database.users[username]) {
savedArticle = upvote(savedArticle, username);
response.body = {article: savedArticle};
response.status = 200;
} else {
response.status = 400;
}
saveDatabase(database);
return response;
}
function downvoteArticle(url, request) {
const id = Number(url.split('/').filter(segment => segment)[1]);
const username = request.body && request.body.username;
let savedArticle = database.articles[id];
const response = {};
if (savedArticle && database.users[username]) {
savedArticle = downvote(savedArticle, username);
response.body = {article: savedArticle};
response.status = 200;
} else {
response.status = 400;
}
saveDatabase(database);
return response;
}
function upvote(item, username) {
if (item.downvotedBy.includes(username)) {
item.downvotedBy.splice(item.downvotedBy.indexOf(username), 1);
}
if (!item.upvotedBy.includes(username)) {
item.upvotedBy.push(username);
}
return item;
}
function downvote(item, username) {
if (item.upvotedBy.includes(username)) {
item.upvotedBy.splice(item.upvotedBy.indexOf(username), 1);
}
if (!item.downvotedBy.includes(username)) {
item.downvotedBy.push(username);
}
return item;
}
// Write all code above this line.
const http = require('http');
const url = require('url');
const port = process.env.PORT || 4000;
const isTestMode = process.env.IS_TEST_MODE;
const requestHandler = (request, response) => {
const url = request.url;
const method = request.method;
const route = getRequestRoute(url);
if (method === 'OPTIONS') {
var headers = {};
headers["Access-Control-Allow-Origin"] = "*";
headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS";
headers["Access-Control-Allow-Credentials"] = false;
headers["Access-Control-Max-Age"] = '86400'; // 24 hours
headers["Access-Control-Allow-Headers"] = "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept";
response.writeHead(200, headers);
return response.end();
}
response.setHeader('Access-Control-Allow-Origin', null);
response.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
response.setHeader(
'Access-Control-Allow-Headers', 'X-Requested-With,content-type');
if (!routes[route] || !routes[route][method]) {
response.statusCode = 400;
return response.end();
}
if (method === 'GET' || method === 'DELETE') {
const methodResponse = routes[route][method].call(null, url);
!isTestMode && (typeof saveDatabase === 'function') && saveDatabase();
response.statusCode = methodResponse.status;
response.end(JSON.stringify(methodResponse.body) || '');
} else {
let body = [];
request.on('data', (chunk) => {
body.push(chunk);
}).on('end', () => {
body = JSON.parse(Buffer.concat(body).toString());
const jsonRequest = {body: body};
const methodResponse = routes[route][method].call(null, url, jsonRequest);
!isTestMode && (typeof saveDatabase === 'function') && saveDatabase();
response.statusCode = methodResponse.status;
response.end(JSON.stringify(methodResponse.body) || '');
});
}
};
const getRequestRoute = (url) => {
const pathSegments = url.split('/').filter(segment => segment);
if (pathSegments.length === 1) {
return `/${pathSegments[0]}`;
} else if (pathSegments[2] === 'upvote' || pathSegments[2] === 'downvote') {
return `/${pathSegments[0]}/:id/${pathSegments[2]}`;
} else if (pathSegments[0] === 'users') {
return `/${pathSegments[0]}/:username`;
} else {
return `/${pathSegments[0]}/:id`;
}
}
if (typeof loadDatabase === 'function' && !isTestMode) {
const savedDatabase = loadDatabase();
if (savedDatabase) {
for (key in database) {
database[key] = savedDatabase[key] || database[key];
}
}
}
const server = http.createServer(requestHandler);
server.listen(port, (err) => {
if (err) {
return console.log('Server did not start succesfully: ', err);
}
console.log(`Server is listening on ${port}`);
});