-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.js
61 lines (49 loc) · 1.24 KB
/
api.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
const PORT = 8080;
const express = require('express');
const fs = require('fs-extra');
const cors = require('cors');
const app = express();
app.use(cors());
const jokes = {
all: [],
byType: []
}
async function loadJokes() {
const data = await fs.readJson('jokes.json');
for await (const element of Object.entries(data)) {
if (element[1].text.length > 0) {
jokes.all.push(element[1]);
let typ = element[1].typ;
if (typ && typ.length > 0) {
typ = typ.toLowerCase();
if (!jokes.byType.typ) {
jokes.byType.typ = [];
}
jokes.byType.typ.push(element[1]);
}
}
}
console.log(`${jokes.all.length} jokes loaded!`)
}
app.get('/', (req, res) => {
res.json({
message: 'API Routes',
routes: [
'/all',
'/random'
]
})
})
app.get('/all', (req, res) => {
res.json(jokes.all);
})
app.get('/random', (req, res) => {
const index = Math.floor(Math.random() * jokes.all.length);
res.json(jokes.all[index]);
})
async function init() {
await loadJokes();
app.listen(PORT);
console.log(`App started, port: ${PORT}`);
}
init();