This repository has been archived by the owner on Jan 28, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
index.js
80 lines (78 loc) · 2.09 KB
/
index.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
var http = require("http")
var https = require("https")
module.exports = {
shorten: function(url, cb) {
if (typeof cb === "function") {
https.get('https://tinyurl.com/api-create.php?url=' + encodeURIComponent(url), res => {
res.on('data', chunk => {
cb(chunk.toString())
})
}).on("error", err => {
cb(null, err)
})
} else {
return new Promise((resolve, reject) => {
https.get('https://tinyurl.com/api-create.php?url=' + encodeURIComponent(url), res => {
res.on('data', chunk => {
resolve(chunk.toString())
})
}).on("error", err => {
reject(err)
})
})
}
},
shortenWithAlias: function(data, cb) {
const url = 'https://tinyurl.com/api-create.php?url=' + encodeURIComponent(data.url) + '&alias=' + encodeURIComponent(data.alias);
if (typeof cb === "function") {
https.get(url, res => {
res.on('data', chunk => {
cb(chunk.toString())
})
}).on("error", err => {
cb(null, err)
})
} else {
return new Promise((resolve, reject) => {
https.get(url, res => {
res.on('data', chunk => {
resolve(chunk.toString())
})
}).on("error", err => {
reject(err)
})
})
}
},
resolve: function(url, cb) {
if (typeof cb === "function") {
if (url.split(':')[0] == 'http') {
proto = http
} else {
proto = https
}
proto.get(url, res => {
if (res.headers.location) cb(res.headers.location);
else cb(null, new Error("Tiny URL not found!"));
})
.on("error", err => {
cb(null, err);
});
} else {
return new Promise((resolve, reject) => {
if (url.split(':')[0] == 'http') {
proto = http
} else {
proto = https
}
proto.get(url, res => {
if (res.headers.location) resolve(res.headers.location);
else reject(new Error("Tiny URL not found!"));
})
.on("error", err => {
reject(err);
});
});
}
}
};