-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
70 lines (58 loc) · 1.85 KB
/
index.js
File metadata and controls
70 lines (58 loc) · 1.85 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
import cors from 'cors';
import express from 'express';
import got from 'got';
const app = express();
const port = process.env.PORT;
app.use(cors());
app.get('/', (req, res) => {
res.status(200).json({
status: 200,
message: 'Success!'
});
});
app.get('/api/:subreddit', (req, res) => {
const subreddit = req.params.subreddit;
got(`https://www.reddit.com/r/${subreddit}/random/.json`).then(response => {
const meme = JSON.parse(response.body);
if(meme[0] === undefined) {
res.status(404).json({
success: false,
message: 'The requested resouce cannot be fetched or does not exist.'
});
}
else {
const { title, permalink, url: image, ups: upvotes, downs: downvotes, num_comments: comments } = meme[0].data.children[0].data;
const memeData = {
title: title,
url: `https://www.reddit.com${permalink}`,
image: image,
upvotes: upvotes,
downvotes: downvotes,
comments: comments
};
const memeDataFormat = {
success: true,
data: memeData
};
res.status(200).json(memeDataFormat);
}
}).catch(error => {
const errorHandler = new Promise((resolve, reject) => {
reject(error);
throw res.status(404).json({
success: false,
message: 'The requested resouce cannot be fetched or does not exist.'
});
});
errorHandler.catch(error => {/* Error handled. */});
});
});
app.get("*", (req, res) => {
res.status(404).json({
status: 404,
message: 'Page not found.'
});
});
app.listen(port, () => {
console.log(`App is listening on port ${port}.`);
});