-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
52 lines (36 loc) · 1015 Bytes
/
server.js
File metadata and controls
52 lines (36 loc) · 1015 Bytes
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
var express = require('express');
var mongoose = require('mongoose');
var bijective = require('./bijective.js');
var Urls = require('./models');
mongoose.connect('mongodb://localhost/url-shortener');
var app = express();
app.use(express.static('public'));
app.get('/url/:longUrl', function(req, res){
var shortUrl = '';
Urls.findOne({url: req.params.longUrl}, function (err, doc){
if (doc){
res.send({'key': bijective.encode(doc._id)});
} else {
var newUrl = Urls({
url: req.params.longUrl
});
newUrl.save(function(err) {
if (err) console.log(err);
res.send({'key': bijective.encode(newUrl._id)});
});
}
});
});
app.get('/:key', function(req, res){
var id = bijective.decode(req.params.key);
Urls.findOne({_id: id}, function (err, doc){
if (doc) {
res.redirect(doc.url);
} else {
res.redirect("/");
}
});
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
});