-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
140 lines (123 loc) · 3.14 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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
(function() {
var EventEmmitter, URL, URLSchema, app, bodyParser, express, mongoose, uniqueId, validate;
EventEmmitter = (require("events")).EventEmmitter;
express = require("express");
mongoose = require('mongoose');
bodyParser = require('body-parser');
validate = require("./validate");
uniqueId = require("./unique_id");
mongoose.connect('mongodb://localhost/urlshorten');
app = express();
app.use(bodyParser.urlencoded({
extended: true
}));
URLSchema = mongoose.Schema({
id: String,
url: String
});
URLSchema.index({
id: 1,
url: 1,
unique: true
});
URL = mongoose.model('URL', URLSchema);
app.get("/", function(req, res) {
return res.json({
code: 200,
url: "/"
});
});
app.get("/:id", function(req, res) {
var id;
id = req.params.id;
return URL.findOne({
id: id
}, function(err, url) {
var ret;
if (err) {
res.status(500);
} else {
if (url != null) {
ret = {
code: 200,
url: url.url
};
} else {
ret = {
code: 404,
info: "not found"
};
}
}
return res.json(ret);
});
});
app.post("/", function(req, res) {
var domain, url;
url = req.body.url;
if (url == null) {
return res.json({
code: 400,
info: "Bad request"
});
} else {
if (validate(url)) {
domain = req.header("Host");
return URL.findOne({
url: url
}, function(err, result) {
var generateShortURL, interval;
if (err) {
console.error(err);
return res.status(500);
} else {
if (result != null) {
return res.json({
code: 200,
short: domain + "/" + result.id
});
} else {
generateShortURL = function() {
var id;
id = uniqueId();
return URL.findOne({
id: id
}, function(err, result) {
var url_;
if (err) {
console.log(err);
}
if (result == null) {
url_ = new URL({
id: id,
url: url
});
url_.save(function(err, url_) {
if (err) {
console.error(err);
return res.status(500);
} else {
return res.json({
code: 200,
short: domain + "/" + url_.id
});
}
});
return clearInterval(interval);
}
});
};
return interval = setInterval(generateShortURL, 0);
}
}
});
} else {
return res.json({
code: 400,
info: "Invalid url"
});
}
}
});
app.listen(3000, "127.0.0.1");
}).call(this);