-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
61 lines (53 loc) · 1.62 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
const express = require("express");
const app = express();
const path = require("path");
// importing the URL from DB
const URL = require("./dbConfig");
// configuring nonoid
const { customAlphabet } = require("nanoid");
const alphabet =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
const nanoid = customAlphabet(alphabet, 8);
const PORT = process.env.PORT || 1337;
app.use(express.urlencoded({ extended: false }));
app.set("view engine", "ejs");
app.use(express.static(path.join(__dirname, "public")));
app.listen(PORT, () => console.log(`app listening on port: ${PORT}`));
// index or '/' route
app.get("/", (req, res) => {
res.render("index", { shrinkedUrl: "" });
});
app.post("/", async (req, res) => {
const fullUrl = req.protocol + "://" + req.get("host") + "/";
// console.log(fullUrl);
// console.log(req.body.urlInput);
try {
// generate nanoid
const id = await nanoid();
// console.log(id, typeof id);
// check if the id already exists
// if id not in DB add url and id to the DB
const url = new URL({
url: req.body.urlInput,
slug: id,
});
const flag = await url.save();
// console.log("flag:", flag);
res.render("index", { shrinkedUrl: fullUrl + id });
} catch (error) {
console.log(error);
}
});
app.get("/:slug", async (req, res) => {
try {
const slug = req.params.slug;
const results = await URL.find({ slug: slug });
if (!results.length) {
return res.send("<h1>URL not found/expired");
}
res.redirect(results[0].url);
} catch (error) {
console.log(error);
res.send("<h1>404 Internal error");
}
});