-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
103 lines (89 loc) · 2.46 KB
/
app.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
93
94
95
96
97
98
99
100
101
102
103
const express = require("express");
const bodyParser = require("body-parser");
const { nanoid } = require('nanoid')
require("dotenv").config();
const mongoose = require("mongoose");
const app = express();
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({ extended: true }));
mongoose.connect(process.env.MONGO_URL, {
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
});
const linkSchema = new mongoose.Schema({
identifier: {
required: true,
type: String,
},
url: {
required: true,
type: String,
},
clicks: {
required: true,
type: Number,
default: 0,
}
});
const Link = mongoose.model("Link", linkSchema);
app.get('/', async(req, res) => {
const links = await Link.find()
res.render('index', { links: links })
});
app.post('/shorten', async(req, res) => {
if (req.body.PW == process.env.PW){
let id = null
while (1) {
id = nanoid(7)
if (await Link.exists({ identifier: id })) continue;
else break;
}
let url = req.body.URL
if (!(url.startsWith('https://') || url.startsWith('http://'))) {
url = 'http://' + url
}
await Link.create({
identifier: id,
url: url,
clicks: 0
})
res.redirect('/')
}else{
res.send(`<div style="display: flex; justify-content: center;">
<h1>Wrong Password</h1>
</div> `)
}
});
app.post('/delete', (req, res) => {
if (req.body.PW == process.env.PW) {
Link.findOneAndRemove({ identifier: req.body.ID }, (err, deleted) => {
if (err) {
console.log(err)
} else {
console.log(deleted)
}
})
res.redirect('/')
}else{
res.send(`<div style="display: flex; justify-content: center;">
<h1>Wrong Password</h1>
</div> `)
}
})
app.get('/:url', (req, res) => {
Link.findOne({ identifier: req.params.url }).then( (link) => {
if (link === undefined) {
res.send(`<div style="display: flex; justify-content: center;">
<h1>Link Not Found</h1>
</div> `)
}else{
link.clicks++;
link.save()
res.redirect(link.url)
}
})
})
app.listen(process.env.PORT || 3000);