-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
52 lines (46 loc) · 1.33 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
const express = require('express');
const { factorial } = require('./factorial');
const app = express();
app.get('/', (req, res) => {
const { host } = req.headers;
res.status(200).json({
message: 'Welcome to the Factorial calculator 🎊',
docs: `http://${host}/docs`,
});
});
app.get('/docs', (req, res) => {
const { host } = req.headers;
res.status(200).json({
message: 'Documentation',
request: `http://${host}/factorial/<number>`,
response: 'The factorial of <number> is <result>`',
example: {
request: `http://${host}/factorial/5`,
response: 'The factorial of 5 is 120`',
},
});
});
app.get('/factorial/:number', (req, res) => {
const { number } = req.params;
if (isNaN(number)) {
return res
.status(400)
.json({ message: `'${req.params.number}' is not a number.` });
}
if (number > 200) {
return res
.status(200)
.json({ message: `The factorial of ${number} is Infinity` });
}
return res
.status(200)
.json({ message: `The factorial of ${number} is ${factorial(number)}` });
});
app.get('*', (req, res) => {
const { host } = req.headers;
res
.status(404)
.json({ message: 'Resource not found.', docs: `http://${host}/docs` });
});
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}`));