Skip to content

Instantly share code, notes, and snippets.

@phillipharding
Created August 22, 2014 15:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phillipharding/ee9fe08278290148b1b0 to your computer and use it in GitHub Desktop.
Save phillipharding/ee9fe08278290148b1b0 to your computer and use it in GitHub Desktop.
Javascript module for shortening URLs using Google (goo.gl)
(function($,window) {
"use strict";
window.pdogs = window.pdogs || {};
pdogs.urlshortener = function() {
var
_googlAPIKey = '<YOUR GOOGLE APIKey HERE>',
_module = { shorten: shorten };
return _module;
function shorten(longUrl, sync) {
var p = $.Deferred();
if (typeof longUrl === 'undefined' || !longUrl || !longUrl.length) {
p.reject({ error: 'Invalid/Empty URI' });
return p.promise();
}
var
decodedLongUrl = decodeURIComponent(longUrl),
params = 'key='+_googlAPIKey,
r = {
type: 'POST',
url: 'https://www.googleapis.com/urlshortener/v1/url?' + params,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
data: "{ longUrl: '" + decodedLongUrl + "' }",
async: !sync
};
jQuery.support.cors = true;
$.ajax(r)
.done(function(response) {
if (response.error) p.reject({ error: '[' + response.error.code+'] ' + response.error.message });
else
p.resolve({ shortUrl: response.id, shortUrlImg: response.id + '.qr', longUrl: response.longUrl });
})
.fail(function(xhr,textStatus, error) {
var m = error.message ? error.message : error;
p.reject({ error: 'goo.gl] ' + textStatus + ': ' + m });
});
return p.promise();
}
}();
})(jQuery,window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment