-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.js
90 lines (84 loc) · 2.65 KB
/
handlers.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
const fs = require('fs');
const path = require('path');
const getTopic = require('./get_topic');
const getTrending = require('./get_trending');
const postUpvote = require('./post_upvote');
const handleHomeRoute = (req, res) => {
const filePath = path.join(__dirname, '..', 'public', 'index.html');
fs.readFile(filePath, (error, file) => {
if (error) {
res.writeHead(500, 'Content-Type:text/html');
res.end('<h1>Sorry, this shit is ass</h1>');
} else {
res.writeHead(200, 'Content-Type:text/html');
res.end(file);
}
});
};
const handlePublic = (req, res, url) => {
const extension = url.split('.')[1];
const extensionType = {
html: 'text/html',
css: 'text/css',
js: 'application/javascript',
ico: 'image/x-icon',
};
const filePath = path.join(__dirname, '..', url);
fs.readFile(filePath, (error, file) => {
if (error) {
res.writeHead(500, 'Content-Type:text/html');
res.end('<h1>Soz, no can do</h1>');
} else {
res.writeHead(200, `Content-Type: ${extensionType[extension]}`);
res.end(file);
}
});
};
const handleTopic = (req, res, url) => {
const topicQuery = url.split('?topic=')[1];
getTopic(topicQuery, (err, file) => {
if (err) return err;
const topicResponse = JSON.stringify(file);
res.writeHead(200, { 'content-type': 'application/json' });
res.end(topicResponse);
})
};
const handleTrending = (req, res) => {
getTrending((err, file) => {
if (err) return err;
const trendingResponse = JSON.stringify(file);
res.writeHead(200, { 'content-type': 'application/json' });
res.end(trendingResponse);
});
};
const handlePostUpvote = (req, res, url) => {
// dream query ?upvote=wtfeventloop+current=javascript
const titleName = url.split('?upvote=')[1].split('+current=')[0];
const currentPage = url.split('+current=')[1].replace(/%20/gi,' ');
postUpvote(titleName, (err, file) => {
if (err) return err;
//if no error call getTrending or getTopic to return the updated info for the DOM
if (currentPage === 'Trending'){
getTrending((err, response) => {
if (err) return err;
const trendingResponse = JSON.stringify(response);
res.writeHead(200, { 'content-type': 'application/json' });
res.end(trendingResponse);
});
} else {
getTopic(currentPage, (err, response) => {
if (err) return err;
const topicResponse = JSON.stringify(response);
res.writeHead(200, { 'content-type': 'application/json' });
res.end(topicResponse);
})
}
});
};
module.exports = {
handleHomeRoute,
handlePublic,
handleTopic,
handleTrending,
handlePostUpvote,
};