-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
83 lines (77 loc) · 2.25 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
//get requirements
var bodyParser = require("body-parser");
var cors = require("cors");
var express = require("express");
var mongoose = require("mongoose");
var { url } = require("./models/url");
require("dotenv/config");
mongoose.Promise = global.Promise;
mongoose.connect(process.env.MONGODB_URI || "mongodb://localhost:27017/url");
var app = express();
app.use(express.static(__dirname + "/public"));
// creates the database entry
// (*) accepts all argument after /new/ regardless of how it's formatted
app.get("/new/:targetURL(*)", (req, res) => {
var { targetURL } = req.params;
var regex = /[-a-zA-Z0-9@:%\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi;
if (regex.test(targetURL) == true) {
var short = Math.floor(Math.random() * 100000).toString();
function findLoop() {
url
.findOne({ shortenURL: short })
.then(rng => {
if (rng) {
short = Math.floor(Math.random() * 100000).toString();
console.log(short);
findLoop();
} else {
var data = new url({
originalURL: targetURL,
shortenURL: short
});
data.save(err => {
if (err) {
return res.send("Error saving to db");
}
});
return res.json(data);
}
})
.catch(err => {
if (err) {
return res.send("Error checking short");
}
});
}
findLoop();
} else {
return res.json({ targetURL: "fail" });
}
});
// use shorten URL
app.get("/:shortenURL(*)", (req, res) => {
let { shortenURL } = req.params;
url
.findOne({ shortenURL })
.then(url => {
if (!url) {
return res.send(
"This shorten URL doesn't correspond to any original URL"
);
}
if (
url.originalURL.slice(0, 7) == "http://" ||
url.originalURL.slice(0, 8) == "https://"
) {
return res.redirect(url.originalURL);
}
res.redirect("http://" + url.originalURL);
})
.catch(err => {
return new Error("Can't redirect to website");
});
});
// listen to see port
app.listen(process.env.PORT, () => {
console.log(`Listening to port ${process.env.PORT}...`);
});