-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathurl-shortener.js
85 lines (76 loc) · 2.68 KB
/
url-shortener.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
var express = require('express');
var app = express();
var helmet = require('helmet');
var bodyParser = require('body-parser');
var db = require('./db');
var isValidURL = require('validator').isURL;
var urlOptions = {
protocols: ['http','https'],
require_tld: true,
require_protocol: false,
require_host: true,
require_valid_protocol: true,
allow_underscores: false,
host_whitelist: false,
host_blacklist: false,
allow_trailing_dot: false,
allow_protocol_relative_urls: false
}
var port = 3002;
// Set up middleware here
var allowCrossDomain = function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
next();
};
app.use(helmet());
app.use('/static', express.static('public'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(allowCrossDomain);
app.get('/', function (req, res) {
res.sendFile(__dirname + "/public/new-link.html", function (err) {
if (err) {
console.error(err);
res.status(500).end("Error");
}
});
});
// This route will catch any GET requests that start with /new/[url]. This is necessary to include the double slashes in http:// or https://
app.get(/\/new\/(http(s?):\/\/)?(.*)/, function (req, res) {
// If protocol wasn't included, default to http://
var longUrl = req.params[0] == undefined ? "http://" + req.params[2] : req.params[0] + req.params[2];
if (isValidURL(longUrl, urlOptions)) {
db.addLink(longUrl)
.then((result) => {res.json(result)})
.catch((err) => {res.status(500).end(err)});
} else {
res.status(400).json({"error": "invalid URL"});
}
});
app.post(['/new', '/api/shorturl/new'], function (req, res) {
var longURL = String(req.body.url).substr(0, 4).toLowerCase() == "http" ? String(req.body.url) : "http://" + String(req.body.url);
if (isValidURL(longURL, urlOptions)) {
db.addLink(longURL)
.then((result) => {res.json(result)})
.catch((err) => {res.status(500).end(err)});
} else {
res.status(200).json({"error": "invalid URL"});
}
});
app.get(['/:short_url', '/api/shorturl/:short_url'], function (req, res) {
db.getLink(req.params.short_url)
.then(function (link) { res.redirect(link); })
.catch(function (err) { res.status(404).end("URL Not Found"); });
});
// Start app
db.connect()
.then(function () {
app.listen(port, 'localhost', function () {
console.log("URL Shortener listening on port " + port);
});
})
.catch(function (err) {
console.log("Error connecting to database: " + err);
process.exit(1);
});
module.exports.app = app;
module.exports.db = db;