This repository has been archived by the owner on Aug 10, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
88 lines (70 loc) · 2.36 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
// server.js
// where your node app starts
// init project
var express = require('express');
var shortid = require("shortid")
var urlvalid = require("tldjs")
var app = express();
var mongo = require("mongodb").MongoClient
var config = require("./config")
var url = "mongodb://" + config.db.host + "/" + config.db.name
shortid.characters('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$@');
// we've started you off with Express,
// but feel free to use whatever libs or frameworks you'd like through `package.json`.
// http://expressjs.com/en/starter/static-files.html
app.use(express.static('public'));
app.use(express.static("views"));
app.get("/new/:url(*)", function(req, res){
mongo.connect(url, function(err, db){
var collection = db.collection("urls")
var url = req.params.url
console.log("connected")
if(err){console.error(err)}
if(urlvalid.parse(url).tldExists && urlvalid.parse(url).isValid){
console.log(urlvalid.parse(url).tldExists)
collection.findOne({"url": url}, {short: 1, _id: 0}, function(err, data){
if(data != null){
res.json({url: url, short:"https://url-shortening.glitch.me/"+data.short})
db.close()
}
else {
var newid = shortid.generate()
res.json({url: url,short: "https://url-shortening.glitch.me/"+newid})
collection.insert([{url: url, short: newid}])
db.close()
}
})
}
else {
res.json({error: "Wrong url format, make sure you have a valid protocol and real site"})
}
})
})
app.get("/:short", function(req, res){
var shortlink = req.params.short
mongo.connect(url, function(err, db){
var collection = db.collection("urls")
if(err){console.error(err)}
else {
collection.findOne({"short": shortlink}, {url: 1, _id: 0}, function(err, data){
if(err){
res.json({error: "URL not found"})
}
else {
res.redirect(data.url)
}
})
}
db.close()
})
})
function newLink (db, callback){
}
// http://expressjs.com/en/starter/basic-routing.html
app.get("/", function (request, response) {
response.sendFile(__dirname + '/index.html');
});
// listen for requests :)
var listener = app.listen(process.env.PORT, function () {
console.log('Your app is listening on port ' + listener.address().port);
});