Skip to content

Instantly share code, notes, and snippets.

@stephen
Last active August 29, 2015 14:08
Show Gist options
  • Save stephen/e9e0e5c64ae771f4831a to your computer and use it in GitHub Desktop.
Save stephen/e9e0e5c64ae771f4831a to your computer and use it in GitHub Desktop.
unwraps a url from shorteners. assumes request is available.
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