This repository was archived by the owner on Feb 16, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
59 lines (51 loc) · 1.56 KB
/
Copy pathserver.js
File metadata and controls
59 lines (51 loc) · 1.56 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
const mongoose = require('mongoose');
const express = require('express');
const GenShortURL = require('./models/genShortURL');
const app = express();
const port = 9000;
// create db
mongoose.connect('mongodb://localhost/urlDB', {
useNewUrlParser: true, useUnifiedTopology: true
})
app.set('view engine', 'ejs');
app.use(express.urlencoded({extended: false}))
app.get('/', async(req,res) => {
const UrlList = await GenShortURL.find();
res.render('index', {UrlList: UrlList, port: port});
})
// If long URL not in db, create document for it and generate short URL
app.post('/genShortURL', async(req,res) => {
const inputUrl = req.body["bigURL"];
console.log(inputUrl);
// inputUrl = addSlash(inputUrl);
console.log(inputUrl);
const doesLongExist = await GenShortURL.exists({ longUrl: inputUrl });
if (doesLongExist == false){
const newUrlPair = GenShortURL({
longUrl: inputUrl,
shortUrl: ""
});
newUrlPair.shortUrl = newUrlPair.id.toString().slice(-6);
newUrlPair.save(function(err){
console.log("URL added successfully");
})
}
res.redirect('/');
})
// Basic URL normalization case
// function addSlash(url) {
// if (url.slice(-1) != '/'){
// url = url + '/';
// return url;
// }
// else {
// return url;
// }
// }
// Get associated long URL from MongoDB and redirect
app.get('/:shortURL', async(req,res) => {
const shortURL = await GenShortURL.findOne({shortUrl: req.params.shortURL});
if (shortURL == null) return res.sendStatus(404);
res.redirect(shortURL.longUrl);
})
app.listen(process.env.PORT || port);