-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
75 lines (56 loc) · 2.01 KB
/
index.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
const express = require("express");
const app = express();
const port = 3000;
const path = require('path');
const jokes = require("./jokesData");
// Serve static files from the Frontend directory
app.use(express.static(path.join(__dirname, './Frontend')));
// Jokes Data
const programmingJokes = require("./programmingJokes");
const scienceJokes = require("./scienceJokes");
const sportsJokes = require("./sportsJokes");
const medicalJokes = require("./medicalJokes");
const generalJokes = require("./generalJokes");
const animalJokes = require("./animalJokes");
// callbacks
function callbackFn1(req,res){
const randomJoke = jokes[Math.floor(Math.random() * jokes.length)];
res.json({joke:randomJoke});
}
function getRandomJoke(category) {
switch (category) {
case 'general':
return generalJokes[Math.floor(Math.random() * generalJokes.length)];
case 'medical':
return medicalJokes[Math.floor(Math.random() * medicalJokes.length)];
case 'sports':
return sportsJokes[Math.floor(Math.random() * sportsJokes.length)];
case 'science':
return scienceJokes[Math.floor(Math.random() * scienceJokes.length)];
case 'programming':
return programmingJokes[Math.floor(Math.random() * programmingJokes.length)];
case 'animal':
return animalJokes[Math.floor(Math.random() * animalJokes.length)];
default:
return -1;
}
}
function callbackFn2(req,res){
const category = req.params.category;
const joke = getRandomJoke(category);
if(joke === -1){
res.json({error: "Invalid Category"});
}else{
res.json(joke);
}
}
// Request Handlers
// Route to serve index.html at the root route
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, './Frontend/index.html'));
});
app.get("/api/joke/random",callbackFn1);
app.get("/api/joke/random/:category", callbackFn2);
app.listen(port,()=>{
console.log("Server is running on port "+port);
});