-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
77 lines (63 loc) · 1.67 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
const express = require("express");
const shortid = require("shortid");
const mongoose = require("mongoose");
const createHttpError = require("http-errors");
const path = require("path");
const shortUrl = require("./models/url.model");
const app = express();
mongoose
.connect("mongodb://localhost:27017", {
useNewUrlParser: true,
dbName: "ShortUrl",
})
.then(() => {
console.log("Mongo connected");
});
app.use(express.static(path.join(__dirname, "public")));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.set("view engine", "ejs");
app.get("/", async (req, res, next) => {
res.render("index");
});
app.post("/", async (req, res, next) => {
try {
const { url } = req.body;
if (!url) {
throw createHttpError.BadRequest("Provide a valid url");
}
const duplicate = await shortUrl.findOne({ url: url });
console.log("Duplicate");
// res.send(duplicate.shortId)
if (duplicate) {
res.render("index", {
short_url: `http://dwarfLink/${duplicate.shortId}`,
real_url: url
});
return;
}
const newshortUrl = new shortUrl({
url: url,
shortId: shortid.generate(),
});
const result = await newshortUrl.save();
res.render("index", {
short_url: `http://dwarfLink/${result.shortId}`,
real_url: url
});
return;
} catch (error) {
console.log(error);
next();
}
});
app.use((req, res, next) => {
next(createHttpError.NotFound())
});
app.use((err, req, res, next) => {
res.status(err.status || 500);
res.render("index", { error: err.message });
});
app.listen(5000, () => {
console.log(`server running on port 5000`);
});