-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
113 lines (101 loc) · 2.65 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
require("dotenv").config();
const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");
const app = express();
require("./database");
let UrlModel = require("./url");
require('./first_url_intiate')
const dns = require("node:dns");
// Basic Configuration
const port = process.env.PORT || 3000;
//middleware on post
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors());
app.use("/public", express.static(`${process.cwd()}/public`));
app.get("/", function (req, res) {
res.sendFile(process.cwd() + "/views/index.html");
});
// Your first API endpoint
app.get("/api/hello", function (req, res) {
res.json({ greeting: "hello API" });
});
app.post("/api/shorturl", function (req, res) {
let url = req.body.url;
let removehttps = /^https:\/\/([^/]*)\/.*/;
let httpsRegex = /^https?:\/\//i;
///^https?:\/\/.+.[.]\w+$/i;
if (httpsRegex.test(url)) {
url = url.replace(removehttps, "$1");
console.log(url);
dns.lookup(url, function (err) {
if (err) {
res.json({ error: "Invalid Hostname" });
} else {
UrlModel.findOne({
original_url: req.body.url,
})
.then((docs) => {
console.log("found", docs);
if (docs == null) {
let newURL = new UrlModel({
original_url: req.body.url,
});
newURL
.save()
.then((docs) => {
console.log("saved", docs);
res.json({
original_url: docs.original_url,
short_url: docs.short_url
});
})
.catch((err) => {
console.log(err);
});
}
else {
res.json({
original_url: docs.original_url,
short_url: docs.short_url
});
}
})
.catch((err) => {
console.log(err);
});
}
});
}
else {
res.json({error: "Invalid URL"});
}
});
//redirection
app.get("/api/shorturl/:url", function (req, res) {
let numRegex = /^\d+$/;
if (numRegex.test(req.params.url)) {
UrlModel.findOne({
short_url: Number(req.params.url)
})
.then(docs=>{
if (docs == null) {
res.json({
error: "No short URL found for the given input",
});
}
else {
res.redirect(docs.original_url);
}
})
.catch(err=>{console.log(err)});
}
else {
res.json({
error: "Wrong format"
});
}
});
app.listen(port, function () {
console.log(`Listening on port ${port}`);
});