-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
54 lines (42 loc) · 1.18 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
const parseUrl = require('url').parse
const http = require('http')
const https = require('https')
function unshortOneTime (url, options={}) {
return new Promise((resolve, reject) => {
var parsed_url = parseUrl(url)
var protocol = (parsed_url.protocol === "https:") ? https : http
var host = parsed_url.host
var path = parsed_url.path
options = Object.assign(options, {host, path})
var req = protocol.request(options, (response) => {
resolve(response.headers && response.headers.location || url)
})
req.on('error', (e) => {
reject(e)
})
req.end()
})
}
function unshortRecursive (urls, options={}, resolve, reject, depth=0) {
if(options.max_depth && options.max_depth === depth)
return resolve(urls)
var long_url = urls[urls.length-1]
unshortOneTime(long_url, options)
.then(unshorted_url => {
if (unshorted_url === long_url)
resolve(urls)
else {
urls.push(unshorted_url)
unshortRecursive(urls, options, resolve, reject, depth+1)
}
})
.catch(reject)
}
function unshort (url, options={}) {
var urls = []
urls.push(url)
return new Promise((resolve, reject) => {
unshortRecursive(urls, options, resolve, reject)
})
}
module.exports = unshort