-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
74 lines (56 loc) · 1.97 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
70
71
72
73
74
const express = require('express');
const mongoose = require('mongoose');
const compression = require("compression");
const helmet = require("helmet");
const { createHttpTerminator } = require("http-terminator");
const ShortUrl = require('./models/shortUrl');
const app = express();
require("dotenv").config();
app.use(compression());
app.use(helmet());
const MONGODB_CONNECTION_URL = process.env.MONGODB_CONNECTION_URL || "mongo://localhost:27017";
mongoose.connect(MONGODB_CONNECTION_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
app.set('view engine', 'ejs');
app.use(express.urlencoded({ extended: false }));
app.get('/', async(req,res) => {
const shortUrls = await ShortUrl.find();
res.render('index', { shortUrls: shortUrls });
});
app.post('/shortUrls', async(req, res) => {
await ShortUrl.create({ full: req.body.fullUrl });
res.redirect('/');
});
app.get('/:shortUrl', async(req, res) => {
const shortUrl = await ShortUrl.findOne({ short: req.params.shortUrl });
// Error Handling if the shorten url doesn't exist
if (shortUrl == null) return res.sendStatus(404);
shortUrl.clicks++
shortUrl.save();
res.redirect(shortUrl.full)
});
const PORT = process.env.PORT || 5000;
const HOSTNAME = process.env.HOSTNAME || "localhost";
const server = app.listen(PORT, HOSTNAME, () => {
console.log(`Server has been launched on ${HOSTNAME}:${PORT}`);
});
const httpTerminator = createHttpTerminator({ server });
async function shutdown(signalOrEvent) {
console.log(`\n${signalOrEvent} occured, shutting down...`);
try {
await httpTerminator.terminate();
console.log("Terminated the server successfully !");
process.exit(0);
} catch (errorShutdown) {
console.error(`Error shutting down the server: ${errorShutdown}`)
process.exit(1);
}
}
// Signals
process.on("SIGINT", shutdown);
process.on("SIGTERM", shutdown);
// Events
process.on("uncaughtException", shutdown);
process.on("unhandledRejection", shutdown);