-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
97 lines (81 loc) · 2.16 KB
/
index.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
import express from "express";
import mongoose from "mongoose";
import { customAlphabet } from "nanoid";
import { config } from "dotenv";
config();
const Schema = mongoose.Schema;
const PORT = process.env.PORT || 5192;
const host = "https://pioneiro-shorturl.herokuapp.com/";
const geturl = (id, parent) => new URL(id, parent).href;
const idSize = 8;
const genid = customAlphabet(
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
idSize
);
const dbURI = process.env.dburi;
const urlSchema = new Schema(
{
_id: {
type: String,
default: genid,
},
url: {
type: String,
required: true,
},
},
{ timestamps: true }
);
const urldb = mongoose.model("URL", urlSchema);
const index = express();
index.set("view engine", "ejs");
index.use(express.static("assets"));
index.use(express.urlencoded({ extended: true }));
mongoose
.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => {
console.log("Connected to DB");
index.listen(PORT, (error) => {
if (error) {
console.log(
"Cannot initiate server due to the following error\n",
error
);
} else {
console.log(`Server initiated at ${host}`);
}
});
});
index.get("/", (req, res) => {
res.render("index");
});
index.post("/newurl", (req, res) => {
const newURL = new URL(req.body.url).href;
urldb.findOne({ url: newURL }, (errorFinding, foundURL) => {
if (errorFinding) {
res.render("error", { error: `Error accessing DB while finding URL` });
} else if (foundURL) {
res.render("result", { url: geturl(foundURL._id, host) });
} else {
new urldb({ url: newURL })
.save()
.then((savedURL) => {
res.render("result", { url: geturl(savedURL._id, host) });
})
.catch((errorSaving) => {
res.render("error", { error: `Error accessing DB whle saving URL` });
});
}
});
});
index.get("/:urlid", (req, res) => {
urldb.findById(req.params.urlid, (error, foundURL) => {
if (error) {
res.render("error", { error: `Error accessing DB while getting URL` });
} else if (foundURL) {
res.redirect(foundURL.url);
} else {
res.render("error", { error: `No URLs found for the given ID` });
}
});
});