-
-
Save glade-at-gigwell/4e080771d685fbf1908edbd98eb2d88c to your computer and use it in GitHub Desktop.
Using the Google Apps Script Cache Service for image blobs and objects above 100Kb
This file contains hidden or 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
function ImageCache(cache) { | |
cache = ChunkyCache(cache || CacheService.getScriptCache()); | |
return { | |
putBlob: function (key, value, timeout) { | |
cache.put(key, Utilities.base64Encode(value.getBytes()), timeout); | |
}, | |
getBlob: function (key) { | |
var rawBytes = cache.get(key); | |
if (rawBytes) { | |
var blob = Utilities.newBlob(""); | |
blob.setBytes(Utilities.base64Decode(rawBytes)); | |
return blob; | |
} | |
return null; | |
}, | |
removeBlob: function (key) { | |
cache.remove(key) | |
} | |
} | |
} | |
function ChunkyCache(cache, chunkSize, defaultTimeout) { | |
var _chunkSize = chunkSize || 100 * 1024; | |
var _timeout = defaultTimeout || 21600000 - 420; | |
return { | |
put: function (key, value, timeout) { | |
timeout = (timeout || _timeout) | |
var asString = ('string' == typeof value); | |
var data = asString ? value : JSON.stringify(value); | |
var cSize = Math.floor(_chunkSize / 2); | |
var itemTimeout = timeout + 5; | |
var chunks = []; | |
var index = 0; | |
while (index < data.length) { | |
cKey = key + "_" + index; | |
chunks.push(cKey); | |
cache.put(cKey, data.substr(index, cSize), itemTimeout + 5); | |
index += cSize; | |
} | |
var manifest = JSON.stringify({ | |
chunkSize: chunkSize, | |
chunks: chunks, | |
asString: asString, | |
length: data.length | |
}); | |
cache.put(key, manifest, timeout); | |
}, | |
get: function (key) { | |
var superBlkCache = cache.get(key); | |
if (superBlkCache != null) { | |
var superBlk = JSON.parse(superBlkCache); | |
chunks = superBlk.chunks.map(function (cKey) { | |
return cache.get(cKey); | |
}); | |
if (chunks.every(function (c) { | |
return c != null; | |
})) { | |
if (superBlk.asString) { | |
return chunks.join(''); | |
} | |
return JSON.parse(chunks.join('')); | |
} | |
} | |
return null; | |
}, | |
remove: function (key) { | |
cache.remove(key) | |
} | |
}; | |
}; | |
function testGetCacheFrom(){ | |
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Data'); | |
var data = sheet.getDataRange().getValues(); | |
var chunky = ChunkyCache(CacheService.getDocumentCache(), 1024*90); | |
chunky.put('Data', data, 120); | |
var check = chunky.get('Data'); | |
var sheetPut = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Out'); | |
for (c in check) { | |
sheetPut.appendRow(check[c]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment