Skip to content

Instantly share code, notes, and snippets.

@selfish
Last active April 30, 2016 23:21
Show Gist options
  • Select an option

  • Save selfish/bb4f968709ef74a0397b9becc33228f1 to your computer and use it in GitHub Desktop.

Select an option

Save selfish/bb4f968709ef74a0397b9becc33228f1 to your computer and use it in GitHub Desktop.
Google Apps Script Cache Util. Will cache values for 6 hours.
// Comfotability util for easy caching using Apps Script DocumentCache.
// Uses md5 for cache keys.
// See: https://developers.google.com/apps-script/reference/cache/cache
var CACHE_INTERVAL = 21600;
var docCache = CacheService.getDocumentCache();
function cacheSet(key, val){
return dcache.put(md5(key), JSON.stringify(val), CACHE_INTERVAL); // Max is: 21600 = 6hours
}
function cacheGet(key){
return JSON.parse(dcache.get(md5(key)));
}
function md5(str){
return Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, str)
.map(function(b) {return ("0" + (b < 0 && b + 256 || b).toString(16)).substr(-2)})
.join("");
}
function get(url){
var res = cacheGet(url);
if(!res){
var httpRes = UrlFetchApp.fetch(url, {muteHttpExceptions:true});
res = JSON.parse(httpRes.getContentText());
if(httpRes.getResponseCode() == 200){
cacheSet(url, res);
} else {
throw "HHTP Get Error: " + res.message
return;
}
}
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment