-
Notifications
You must be signed in to change notification settings - Fork 359
/
Copy pathindex.js
89 lines (71 loc) · 1.97 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
76
77
78
79
80
81
82
83
84
85
86
87
88
const express = require('express');
const LimitingMiddleware = require('limiting-middleware');
const { types, randomJoke, randomTen, randomSelect, jokeByType, jokeById, count } = require('./handler');
const app = express();
app.use(new LimitingMiddleware().limitByIp());
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
next();
});
app.get('/', (req, res) => {
res.send('Try /random_joke, /random_ten, /jokes/random, or /jokes/ten , /jokes/random/<any-number>');
});
app.get('/ping', (req, res) => {
res.send('pong');
});
app.get('/random_joke', (req, res) => {
res.json(randomJoke());
});
app.get('/random_ten', (req, res) => {
res.json(randomTen());
});
app.get('/jokes/random', (req, res) => {
res.json(randomJoke());
});
app.get("/jokes/random/:num", (req, res) => {
let num;
try {
num = parseInt(req.params.num);
if (!num) {
res.send("The passed path is not a number.");
} else {
if (num > count) {
res.send(`The passed path exceeds the number of jokes (${count}).`);
} else {
res.json(randomSelect(num));
}
}
} catch (e) {
return next(e);
}
});
app.get('/jokes/ten', (req, res) => {
res.json(randomTen());
});
app.get('/jokes/:type/random', (req, res) => {
res.json(jokeByType(req.params.type, 1));
});
app.get('/jokes/:type/ten', (req, res) => {
res.json(jokeByType(req.params.type, 10));
});
app.get('/jokes/:id', (req, res, next) => {
try {
const { id } = req.params;
const joke = jokeById(+id);
if (!joke) return next({ statusCode: 404, message: 'joke not found' });
return res.json(joke);
} catch (e) {
return next(e);
}
});
app.get('/types', (req, res, next) => {
res.json(types);
})
app.use((err, req, res, next) => {
const statusCode = err.statusCode || 500;
res.status(statusCode).json({
type: 'error', message: err.message
});
});
const PORT = process.env.PORT || 3005;
app.listen(PORT, () => console.log(`listening on ${PORT}`));