Skip to content

Instantly share code, notes, and snippets.

@mhawksey
Last active April 2, 2021 05:51
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mhawksey/d27604f361cfcce64bfdc54f10ff90d7 to your computer and use it in GitHub Desktop.
Save mhawksey/d27604f361cfcce64bfdc54f10ff90d7 to your computer and use it in GitHub Desktop.
Google Apps Script shim to replace UrlShortener calls with a Bit.ly version
// https://addyosmani.com/blog/essential-js-namespacing/
// extend.js
// written by andrew dupont, optimized by addy osmani
function extend(destination, source) {
var toString = Object.prototype.toString,
objTest = toString.call({});
for (var property in source) {
if (source[property] && objTest == toString.call(source[property])) {
destination[property] = destination[property] || {};
extend(destination[property], source[property]);
} else {
destination[property] = source[property];
}
}
return destination;
};
// replacement for UrlShortener
var UrlShortener = UrlShortener || {};
extend(UrlShortener, {
Util:{
getCachedProperty: function (key){
var cache = CacheService.getScriptCache()
var value = cache.get(key)
if (!value){
var value = PropertiesService.getScriptProperties().getProperty(key);
cache.put(key, value, 86400);
}
return value;
},
setToken: function(token){
PropertiesService.getScriptProperties().setProperty('BITLY_TOKEN', token)
},
setGUID: function(guid){
PropertiesService.getScriptProperties().setProperty('BITLY_GUID', token)
},
CALL_: function(path,options){
var fetchOptions = {method:"",muteHttpExceptions:true, contentType:"application/json", headers:{Authorization:"Bearer "+UrlShortener.Util.getCachedProperty('BITLY_TOKEN')}};
var url = 'https://api-ssl.bitly.com/v4' + path;
for(option in options){
fetchOptions[option] = options[option];
}
var response = UrlFetchApp.fetch(url, fetchOptions);
Logger.log(response.getResponseCode());
if(response.getResponseCode() != 200){
throw new Error(response.getContentText())
}else{
return JSON.parse(response.getContentText());
}
}
},
Url:{
insert: function (obj){
var path = '/shorten';
var callOptions = {method:"POST",payload:JSON.stringify({
"long_url": obj.longUrl,
"group_guid": UrlShortener.Util.getCachedProperty('BITLY_GUID')
})};
var r = UrlShortener.Util.CALL_(path,callOptions)
return {id:r.link};
}
},
Groups:{
list: function(){
var path = '/groups';
var callOptions = {method:"GET"};
return UrlShortener.Util.CALL_(path,callOptions);
}
}
});
@jindrichsirucek
Copy link

setGUID: function(guid){
PropertiesService.getScriptProperties().setProperty('BITLY_GUID', token)
},

this metod needs fix "token" should be guid..

Could you also pls tell me where I can get that guid? I was able to generate token, but i cant get the guid.. thx

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment