-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
69 lines (55 loc) · 1.48 KB
/
server.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
const express = require('express');
const path = require('path');
const axios = require('axios');
const morgan = require('morgan');
const app = express();
const morganMiddleware = morgan(
':method :url :status :res[content-length] - :response-time ms',
{
stream: {
write: (message) => console.log(message.trim()),
},
}
);
app.use(morganMiddleware);
app.use(express.static(path.join(__dirname, 'public')));
app.set('view engine', 'pug');
async function getRandomJoke() {
const response = await axios.get('https://api.chucknorris.io/jokes/random');
return response.data;
}
app.get('/', async (req, res, next) => {
try {
const response = await getRandomJoke();
res.render('home', {
title: 'Random Chuck Norris Jokes',
joke: response,
});
} catch (err) {
next(err);
}
});
app.get('/joke', async (req, res, next) => {
try {
const response = await getRandomJoke();
res.json(response);
} catch (err) {
next(err);
}
});
app.use(function (err, req, res, next) {
console.error(err);
res.set('Content-Type', 'text/html');
res.status(500).send('<h1>Internal Server Error</h1>');
});
const server = app.listen(process.env.PORT || 3000, () => {
console.log(`chucknorris server started on port: ${server.address().port}`);
});
function cleanupAndExit() {
server.close(() => {
console.log('chucknorris server closed');
process.exit(0);
});
}
process.on('SIGTERM', cleanupAndExit);
process.on('SIGINT', cleanupAndExit);