Created
July 27, 2015 17:27
-
-
Save fgandellini/60b74b6ee0a000fb4201 to your computer and use it in GitHub Desktop.
url utils
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 url = require('url'); | |
var request = require('superagent'); | |
var debug = require('debug')('url-utils'); | |
function parse(link) { | |
return new Promise(function(resolve, reject) { | |
try { | |
var parsedUrl = url.parse(link, true, true); | |
if (isValid(parsedUrl)) { | |
return isAvailable(parsedUrl) | |
.then(function(lastRedirectUrl, body) { | |
var parsedLastRedirectUrl = url.parse(lastRedirectUrl, true, true); | |
resolve(parsedLastRedirectUrl); | |
}) | |
.catch(reject); | |
} else { | |
return null; | |
} | |
} catch(ex) { | |
return null; | |
} | |
}); | |
} | |
function isValid(parsedUrl) { | |
var isValid = !isEmpty(parsedUrl) && !isSlack(parsedUrl); | |
debug('parsedUrl is valid ', isValid); | |
return isValid; | |
} | |
function isEmpty(parsedUrl){ | |
var isEmpty = !parsedUrl.host || !parsedUrl.hostname; | |
debug('parsedUrl is empty ', isEmpty); | |
return isEmpty; | |
} | |
function isSlack(parsedUrl) { | |
var isSlack = parsedUrl.hostname === 'slack.com'; | |
debug('parsedUrl is slack ', isSlack); | |
return isSlack; | |
} | |
function isAvailable(parsedUrl) { | |
return new Promise(function(resolve, reject) { | |
request | |
.get(parsedUrl) | |
.end(function(err, res) { | |
if (!err) { | |
debug('parsedUrl is available'); | |
var lastRedirectUrl = res.redirects.pop(); | |
resolve(lastRedirectUrl, res.body); | |
} else { | |
debug('parsedUrl is not available'); | |
reject(); | |
} | |
}); | |
}); | |
} | |
module.exports = { | |
parse: parse | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment