forked from freeCodeCamp/boilerplate-project-urlshortener
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
109 lines (89 loc) · 2.47 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
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
require('dotenv').config();
const bodyParser = require('body-parser');
const express = require('express');
const cors = require('cors');
const dns = require("dns");
const app = express();
const mongoose = require("mongoose");
const { Schema } = mongoose;
const httpsRegex = /http:|https:/g;
// Connect to mongo server
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true });
// Config body parser
app.use(bodyParser.urlencoded({ extended: false }));
// Initiate URL Shortener Schema
const shortenSchema = new Schema({
original_url: { type: String, required: true, unique: true },
short_url: Number
});
let ShortenURL = mongoose.model('ShortenURL', shortenSchema);
// Basic Configuration
const port = process.env.PORT || 3000;
app.use(cors());
app.use('/public', express.static(`${process.cwd()}/public`));
app.get('/', function(req, res) {
res.sendFile(process.cwd() + '/views/index.html');
});
app.post("/api/shorturl", function(req, res, next) {
try {
req.fullURL = new URL(req.body.url);
req.urlDomain = req.fullURL.hostname;
if (req.fullURL.protocol.match(httpsRegex) == null) {
return res.json({
error: "Invalid URL"
});
}
}
catch(err) {
return res.json({
error: "Invalid URL"
});
}
next();
}, function(req, res, next) {
dns.lookup(req.urlDomain, function(err, host) {
if (err) {
return res.json({
error: "Invalid URL"
});
}
req.original_url = req.body.url;
next();
});
}, function(req, res, next) {
ShortenURL.findOne({ original_url: req.original_url }, function(err, data) {
req.existingURL = data;
next();
});
}, function(req, res) {
if (req.existingURL != null) {
const url = JSON.stringify(req.existingURL, ["original_url", "short_url"]);
return res.json(JSON.parse(url));
}
const newShorten = new ShortenURL({
original_url: req.original_url,
short_url: Math.floor(new Date)
});
newShorten.save(function(err, data) {
if (err) {
return res.json({
error: err
});
}
const url = JSON.stringify(data, ["original_url", "short_url"]);
res.json(JSON.parse(url));
});
});
app.get("/api/shorturl/:short_url", function(req, res) {
ShortenURL.findOne({ short_url: parseInt(req.params.short_url) }, function(err, data) {
if (err) {
return res.json({
error: err
});
}
res.redirect(data.original_url);
});
});
app.listen(port, function() {
console.log(`Listening on port ${port}`);
});