forked from dboy1981/url-shortener-node-mongo-express
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
117 lines (89 loc) · 2.75 KB
/
app.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
114
115
116
117
var express = require('express');
var app = express();
var path = require('path');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var Slack = require('slack-node');
var config = require('./config');
var base58 = require('./base58.js');
// grab the url model
var Url = require('./models/url');
mongoose.connect(config.db);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res){
res.sendFile(path.join(__dirname, 'views/index.html'));
});
app.post('/api/shorten', function(req, res){
var longUrl = req.body.url;
var shortUrl = '';
// check if url already exists in database
Url.findOne({long_url: longUrl}, function (err, doc){
if (doc){
shortUrl = config.webhost + base58.encode(doc._id);
// the document exists, so we return it without creating a new entry
res.send({'shortUrl': shortUrl});
} else {
// since it doesn't exist, let's go ahead and create it:
var newUrl = Url({
long_url: longUrl
});
// save the new link
newUrl.save(function(err) {
if (err){
console.log(err);
}
shortUrl = config.webhost + base58.encode(newUrl._id);
res.send({'shortUrl': shortUrl});
});
}
});
});
app.post('/contact', function(req,res){
webhookUri = "https://hooks.slack.com/services/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";
message = {
"attachments":[
{
"fallback":"Message from "+req.body.name,
"pretext":"Message from: "+req.body.name+" "+req.body.email,
"color":"#00D000",
"fields":[
{
"value":req.body.comment,
"short":false
}
]
}
]
};
slack = new Slack();
slack.setWebhook(webhookUri);
slack.webhook(message, function(err, response) {
console.log(response);
});
res.sendFile(path.join(__dirname, 'views/thanks.html'));
});
app.get('/:encoded_id', function(req, res){
var base58Id = req.params.encoded_id;
var id = base58.decode(base58Id);
// check if url already exists in database
Url.findOne({_id: id}, function (err, doc){
if (doc) {
var urls = doc.long_url.split(",");
idx = Math.floor(Math.random() * urls.length);
var url = urls[idx];
console.log(req.params.encoded_id + " redirects to " + url + " (" + (idx + 1) + "/" + urls.length + ")");
res.writeHead(302, {
'Location': url
});
res.end();
/* res.redirect(doc.long_url); */
} else {
res.redirect(config.webhost);
}
});
});
var server = app.listen(config.port, function(){
console.log('Server listening on port ' + config.port);
});