-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
87 lines (79 loc) · 2.54 KB
/
index.js
File metadata and controls
87 lines (79 loc) · 2.54 KB
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
const e = require('express');
const express = require('express');
const shortId = require('shortid');
const mongoose = require('mongoose');
const createHttpError = require('http-errors');
const path = require('path')
const app = express();
const ShortUrl = require('./models/model');
require('dotenv').config()
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.set('view engine', 'ejs')
mongoose.connect(process.env.DB, {
dbName: 'lenk-cf',
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
}).then(() => console.log('Mongoose is connected '))
.catch((error) => console.log("Error"))
app.set('view engine', 'ejs')
app.get('/', async (req, res, next) => {
res.render('index')
})
app.post('/', async (req, res, next) => {
try {
const { url } = req.body
if (!url) {
throw createHttpError.BadRequest('Provide a valid url')
}
const urlExists = await ShortUrl.findOne({ url })
if (urlExists) {
res.render('index', {
// short_url: `${req.hostname}/${urlExists.shortId}`,
short_url: `${req.headers.host}/${urlExists.shortId}`,
})
return
}
const shortUrl = new ShortUrl({ url: url, shortId: shortId.generate() })
const result = await shortUrl.save()
res.render('index', {
/* short_url: `${req.hostname}/${result.shortId}`, */
short_url: `${req.headers.host}/${result.shortId}`,
})
} catch (error) {
next(error)
}
})
app.get('/:shortId', async (req, res, next) => {
try {
const { shortId } = req.params
const result = await ShortUrl.findOne({ shortId })
if (!result) {
throw createHttpError.NotFound('Short url does not exist')
}
res.redirect(result.url)
} catch (error) {
next(error)
}
})
app.set('trust proxy', true);
app.use((req, res, next) => {
if(!req.secure) return res.redirect('https://' + req.get('host') + req.url);
next();
});
app.use((req, res, next) => {
res.send(`HTTPS: ${req.secure}`);
next();
});
app.use((req, res, next) => {
next(createHttpError.NotFound())
})
app.use((err, req, res, next) => {
res.status(err.status || 500)
res.render('index', { error: err.message })
})
app.listen(process.env.PORT || 3000, () => {
console.log('Listening on port 3000');
})