-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
92 lines (74 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
const express = require('express');
const mongoose = require('mongoose');
const ShortUrl = require('./models/shortUrl');
var geoip = require('geoip-lite');
const app = express();
mongoose.connect('mongodb+srv://root:[email protected]/myFirstDatabase?retryWrites=true&w=majority', {
useNewUrlParser: true,
useUnifiedTopology: true
});
// setting ejs as view engine..
app.set('view engine', 'ejs');
app.set('trust proxy', true);
app.use(express.urlencoded({
extended: true
}));
app.get('/', async (req, res) => {
const shortUrls = await ShortUrl.find().sort({
"clicks": -1
});
var labels = [];
var data = [];
var randomColor = ['rgb(255, 99, 132)',
'rgb(54, 162, 235)',
'rgb(255, 205, 86)',
'rgb(225, 90, 32)',
'rgb(54, 12, 25)',
'rgb(55, 225, 6)',
'rgb(215, 5, 86)',
'rgb(225, 90, 32)',
'rgb(54, 2, 25)',
];
var backgroundcolor = [];
shortUrls.forEach((ele) => {
labels.push(ele.short);
data.push(ele.clicks);
var rndIndx = (Math.ceil(Math.random() * 100)) % randomColor.length;
backgroundcolor.push(randomColor[rndIndx]);
});
// console.log(labels);
// console.log(data);
res.render('index', {
shortUrls: shortUrls,
data: data,
labels: labels,
backgroundcolor: backgroundcolor,
});
});
app.post('/shortUrls', async (req, res) => {
// console.log('Headers: ' + JSON.stringify(req.headers));
// console.log('IP: ' + JSON.stringify(req.ip));
//getting region of request
var geo = geoip.lookup(req.ip);
var country = (geo ? geo.country : "Location not detected");
await ShortUrl.create({
full: req.body.fullUrl,
region: country,
});
res.redirect('/');
});
app.get('/:shortUrl', async (req, res) => {
console.log(req.params);
const shortUrl = await ShortUrl.findOne({
short: req.params.shortUrl
});
if (shortUrl == null) {
console.log('Not Find');
return res.sendStatus(404);
}
shortUrl.clicks++;
shortUrl.save();
res.redirect(shortUrl.full);
res.redirect("back");
});
app.listen(process.env.PORT || 5000);