Last active
August 29, 2015 14:08
-
-
Save stephen/e9e0e5c64ae771f4831a to your computer and use it in GitHub Desktop.
unwraps a url from shorteners. assumes request is available.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var unwrapUrl = function(input, callback) { | |
var options = {}; | |
if (typeof(input) === 'string') { | |
options.url = input; | |
} else if (typeof(input) === 'object') { | |
options = input; | |
} | |
options._attempts = options._attempts || 0; | |
options.maxAttempts = options.maxAttempts || 5; | |
if (options._attempts > options.maxAttempts) { | |
if (callback) { | |
callback(new Error('Exceeded max redirect follow attempts (' + options.maxAttempts + ')')); | |
return; | |
} | |
} | |
request({ | |
url: options.url, | |
followRedirect: false | |
}, function(err, response) { | |
if (err) { | |
var newErr = new Error("Error following redirects: " + err.message); | |
newErr.innerError = err; | |
if (callback) callback(newErr); | |
} else { | |
if (response.headers.location) { | |
unwrapUrl({ | |
url: response.headers.location, | |
_attempts: options._attempts + 1, | |
maxAttempts: options.maxAttempts | |
}, callback); | |
} else { | |
if (callback) callback(null, options.url); | |
} | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment