-
Notifications
You must be signed in to change notification settings - Fork 0
/
urlService.js
35 lines (32 loc) · 1.07 KB
/
urlService.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
const urlRegex = /http(s)*:\/\/(www\.)*([a-zA-Z0-9\-])+(\.\w+){1,2}/g;
const urlDao = require("./urlDao");
module.exports = {
short: function short(url, callback) {
var regex = new RegExp(urlRegex);
if (url.match(regex) ) {
urlDao.find(url, getShortUrl.bind(null, url, callback));
} else {
return callback(new Error("URL is not valid. Verify protocol and address"), null);
}
},
find: function find(sequence, callback) {
urlDao.findBySequence(sequence, getBySequence.bind(null, callback));
}
};
function getBySequence(callback, result) {
if (result.length > 0) {
return callback(null, result[0].url);
}
return callback(new Error("Does not exist matching url"), null);
}
function getShortUrl(url, callback, result) {
if (result.length > 0) {
// Url already exists
return callback(null, result[0].seq);
} else {
// New url, save and then return
urlDao.save(url, function(sequence) {
return callback(null, sequence);
});
}
}