-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
70 lines (58 loc) · 1.48 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
const express = require("express");
const app = express();
const mongo = require("mongoose");
const PORT = 3000;
const shortUrl = require("./models/shortUrl");
const methodOverride = require("method-override");
// mongoDb setup
mongo.connect('mongodb://localhost:27017/short_url', {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true
});
app.use(methodOverride("_method"));
app.set("view engine", "ejs");
app.use(express.urlencoded({
extended: false
}))
// Routes
app.get("/", (req, res) => {
shortUrl.find({}, function (err, found) {
if (err) {
console.log(err);
} else {
res.render("index", {
item: found
})
}
})
})
app.post("/shortUrl", async (req, res) => {
await shortUrl.create({
full: req.body.fullUrl
});
res.redirect("/");
})
app.get("/:shortUrl", async (req, res) => {
const url = await shortUrl.findOne({short : req.params.shortUrl});
if(url == null) {
return res.sendStatus(404);
}
url.clicks++;
url.save();
res.redirect(url.full);
})
app.delete("/:id", (req, res) => {
shortUrl.findByIdAndRemove(req.params.id, (err, delete_data) => {
if (err) {
console.log(err);
} else {
console.log("data successful remove!!!");
}
res.redirect("/");
})
})
app.listen(PORT, () => {
console.log(`the server is running on port ${PORT}`);
})