Skip to content
This repository has been archived by the owner on Mar 8, 2021. It is now read-only.

Commit

Permalink
Refactor
Browse files Browse the repository at this point in the history
+ Rewrite code to follow modern node conventions (fixes #2)
+ Replace old "tests" with new BDD tests
+ Bump version to 1.0
  • Loading branch information
spotify-kai committed Apr 10, 2014
1 parent b9dbce9 commit b6eb0f9
Show file tree
Hide file tree
Showing 12 changed files with 480 additions and 149 deletions.
3 changes: 2 additions & 1 deletion .gitignore
@@ -1 +1,2 @@
.npmignore .npmignore
node_modules
45 changes: 35 additions & 10 deletions README.md
Expand Up @@ -4,29 +4,54 @@


## Command-line Usage ## Command-line Usage


goo.gl www.google.com ```bash
goo.gl http://goo.gl/fbsS $ goo.gl www.google.com
goo.gl www.google.com http://goo.gl/fbsS nba.com http://www.google.com -> http://goo.gl/fbsS


It'll automatically shorten or expand single or multiple urls $ goo.gl http://goo.gl/fbsS
http://goo.gl/fbsS -> http://www.google.com/

$ goo.gl www.google.com http://goo.gl/fbsS nba.com
http://goo.gl/fbsS -> http://www.google.com/
http://www.google.com -> http://goo.gl/fbsS
http://nba.com -> http://goo.gl/d1T8

$ goo.gl --key aBcDeFGhIjKLMnOPqRsT www.spotify.com
http://www.spotify.com/ -> http://goo.gl/cJFAL
```

It'll shorten and/or expand one or more URLs at a time.


## Module Usage ## Module Usage


Methods return promises.

```javascript ```javascript
var googl = require('goo.gl'); var googl = require('goo.gl');


// Shorten a long url and output the result // Shorten a long url and output the result
googl.shorten('http://www.google.com/', function (shortUrl) { googl.shorten('http://www.google.com/')
console.log(shortUrl); .then(function (shortUrl) {
}); console.log(shortUrl);
}).
.catch(function (err) {
console.error(err.message);
});




// Set a developer key (see http://goo.gl/4DvFk for more info.) // Set a developer key (see http://goo.gl/4DvFk for more info.)
googl.setKey('aBcDeFGhIjKLMnOPqRsT'); googl.setKey('aBcDeFGhIjKLMnOPqRsT');


// Get currently set developer key
googl.getKey();


// Expand a goo.gl url and output the result // Expand a goo.gl url and output the result
googl.expand('http://goo.gl/fbsS', function (longUrl) { googl.expand('http://goo.gl/fbsS')
console.log(shortUrl); .then(function (longUrl) {
console.log(shortUrl);
})
.catch(function (err) {
console.error(err.message);
});
}); });
``` ```
74 changes: 46 additions & 28 deletions cli.js
@@ -1,33 +1,51 @@
#!/usr/bin/env node #!/usr/bin/env node
(function() {
'use strict';


var googl = require('./lib/googl.js'), var googl = require('./lib/googl.js'),
url = require('url'), commander = require('commander'),
args = process.argv.slice(2), urlParser = require('url').parse;
hostname = null;


if (args.length) { commander
args.forEach(function (val, index, array) { .version(googl.VERSION)
if (typeof url.parse(val).protocol === 'undefined') { .usage('[options] <url ...>')
val = 'http://' + val; .option('-k, --key <api-key>', 'Specify an API key to use')
} .parse(process.argv);


hostname = (typeof url.parse(val).hostname === 'undefined' ? '' : if (commander.args.length) {
url.parse(val).hostname);

if (commander.key) {
if (!hostname) { googl.setKey(commander.key);
console.log('Invalid url: %s', val);
return;
}

if (hostname === 'goo.gl') {
googl.expand(val, function (res) {
console.log('%s -> %s', val, (res.longUrl || JSON.stringify(res)));
});
return;
} }


googl.shorten(val, function (res) { commander.args.forEach(function (url, index, array) {
console.log('%s -> %s', val, (res.id || JSON.stringify(res)));
if (!urlParser(url).protocol) {
url = 'http://' + url;
}

if ('goo.gl' === urlParser(url).hostname) {

googl.expand(url)
.then(function (longUrl) {
console.log('%s -> %s', url, longUrl);
})
.catch(function (err) {
console.error(err.message);
});

} else {

googl.shorten(url)
.then(function (shortUrl) {
console.log('%s -> %s', url, shortUrl);
})
.catch(function (err) {
console.error(err.message);
});

}
}); });
}); }
}
}());
205 changes: 117 additions & 88 deletions lib/googl.js
@@ -1,105 +1,134 @@
var googl = (function () { (function() {
var _url = require('url'), 'use strict';
_https = require('https'),
_querystring = require('querystring'),
_apikey = '';


var request = require('request'),
urlParser = require('url').parse,
Q = require('q'),
API_ENDPOINT = 'https://www.googleapis.com/urlshortener/v1/url',
API_KEY = '',
VERSION = '0.1.0';


function _setKey(key) { /**
_apikey = key || ''; * Send a request to the goo.gl API
module.exports.key = _apikey; * @param {string} type - can be 'shorten' or 'expand'
} * @param {string} url - url to take action on

* @returns {promise}
*/
function _googleRequest(type, url) {
var deferred = Q.defer(),
options = {
uri: API_ENDPOINT,
qs: {},
encoding: 'utf8',
json: true
};


function _getKey () { if (!url || typeof url !== 'string') {
return (_apikey ? _apikey : ''); deferred.reject(new Error('Invalid URL specified'));
} return deferred.promise;
}


if (!urlParser(url).protocol) {
url = 'http://' + url;
}


function _shorten (url, callback) { if (API_KEY && typeof API_KEY === 'string') {
if (!url) { options.qs.key = API_KEY;
console.error('Please specify a valid url.');
return;
} }


if (typeof _url.parse(url).protocol === 'undefined') { switch(type) {
url = 'http://' + url; case 'shorten':
options.method = 'POST';
options.body = { 'longUrl': url };
break;
case 'expand':
options.method = 'GET';
options.qs.shortUrl = url;
break;
default:
deferred.reject(new Error('Invalid operation'));
return deferred.promise;
} }


if (!callback) { callback = false; } request(options, function (error, res, body) {

if (error) {
var key = _getKey(), deferred.reject(error);
options = { } else if (res.statusCode !== 200) {
host: 'www.googleapis.com', error = new Error(res.statusCode + ' - ' + body.error.message);
port: 443, deferred.reject(error);
path: '/urlshortener/v1/url' + (key ? '?' + _querystring.stringify({'key': key}) : ''), } else {
method: 'POST', deferred.resolve(body);
headers: { }
'content-type': 'application/json'
}
};

var req = _https.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (d) {
d = JSON.parse(d);
if (callback) {
callback(d);
} else {
console.log(d.id || d.error);
}
});
}); });

req.on('error', function(e) { console.error(e); });


req.write(JSON.stringify({'longUrl': url})); return deferred.promise;

req.end();
} }


/**
* Shorten a URL
* @param {string} url
* @returns {promise}
*/
function shorten (url) {
var deferred = Q.defer();


function _expand (url, callback) { _googleRequest('shorten', url)
if (!url) { .then(function (json) {
console.error('Please specify a valid url.'); deferred.resolve(json.id);
return; })
} .catch(function (error) {
deferred.reject(error);
});


if (typeof _url.parse(url).protocol === 'undefined') { return deferred.promise;
url = 'http://' + url; }
}

/**
if (!callback) { callback = false; } * Expand a URL

* @param {string} url
var key = _getKey(), * @returns {promise}
options = { */
host: 'www.googleapis.com', function expand (url) {
path: '/urlshortener/v1/url?' + var deferred = Q.defer();
(key ? _querystring.stringify({'key': key, 'shortUrl': url}) :
_querystring.stringify({'shortUrl': url})) _googleRequest('expand', url)
}; .then(function (json) {

deferred.resolve(json.longUrl);
_https.get(options, function(res) { })
res.setEncoding('utf8'); .catch(function (error) {
res.on('data', function (d) { deferred.reject(error);
d = JSON.parse(d);
if (callback) {
callback(d);
} else {
console.log(d.longUrl || d.error);
}
}); });


}).on('error', function(e) { return deferred.promise;
console.error(e);
});
} }


return { /**
'shorten': _shorten, * Set an API key to use when making requests
'expand': _expand, * @param {string} API key
'setKey': _setKey * @returns {string} API key
*/
function setKey (key) {
if (typeof key === 'string') {
API_KEY = key;
}

return API_KEY;
}

/**
* Get currently set API key
* @returns {string} API key
*/
function getKey () {
return API_KEY;
}

module.exports = {
_googleRequest: _googleRequest,
shorten: shorten,
expand: expand,
setKey: setKey,
getKey: getKey,
VERSION: VERSION
}; };
}()); }());

module.exports = googl;

0 comments on commit b6eb0f9

Please sign in to comment.