-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
75 lines (58 loc) · 1.91 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
var shortid = require('shortid');
var express = require('express');
var app = express();
var mongoose = require('mongoose');
mongoose.Promise = global.Promise; //replace depricated mongoose promises
app.set('port', (process.env.PORT || 5000));
mongoose.connect('mongodb://user:[email protected]:49700/shorturl');
var urlSchema = new mongoose.Schema({
longUrl: String,
shortUrl: String,
shortId: String
});
var Url = mongoose.model('Url',urlSchema);
app.get('/url/:id',function(req,res,next){
Url.findOne({shortId:req.params.id}
,function(err,data){
if (err) throw err;
if (!data){
console.log(req.protocol + '://' + req.get('Host') + '/url/' + req.params.id);
res.send('URL not in database');
}
else {
console.log(data.longUrl);
res.redirect('http://' + data.longUrl);
}
next();
});
});
app.get('/:url',function(req,res,next){
// check if url already exists in database
Url.count({longUrl:req.params.url},function(err,count){
if (err) throw err;
if (count === 0){
var newId = shortid.generate();
Url({
longUrl:req.params.url,
shortUrl:req.protocol + '://' + req.get('Host') + '/url/' + newId,
shortId: newId
}).save(function(error){
if (error){throw error;}
console.log(req.get('Host'));
next();
});
}
});
});
app.get('/:url',function(req,res){
Url.findOne({longUrl:req.params.url},function(error,data){
if (error) throw error;
res.send(data);
});
});
app.get('/',function(req,res){
res.send('Append your url to the end of API endpoint without http://');
});
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});