Google Apps Script shim to replace UrlShortener calls with a Bit.ly version
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
// 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); | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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