Skip to content

Instantly share code, notes, and snippets.

@ChrisBaker97
Forked from pilbot/ChunkyCache.gs
Last active February 4, 2022 05:35
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 ChrisBaker97/c19ff5ee1a43a1d68178c74f39962516 to your computer and use it in GitHub Desktop.
Save ChrisBaker97/c19ff5ee1a43a1d68178c74f39962516 to your computer and use it in GitHub Desktop.
Using the Google Apps Script Cache Service for objects above 100Kb
function ChunkyCache(cache, chunkSize){
chunkSize = chunkSize || 100*1024;
return {
put: function (key, value, timeout) {
var json = JSON.stringify(value);
var cSize = Math.floor(chunkSize / 2);
var chunks = [];
var index = 0;
while (index < json.length){
cKey = key + "_" + index;
chunks.push(cKey);
cache.put(cKey, json.substr(index, cSize), timeout+5);
index += cSize;
}
var superBlk = {
chunkSize: chunkSize,
chunks: chunks,
length: json.length
};
cache.put(key, JSON.stringify(superBlk), 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; })){
return JSON.parse(chunks.join(''));
}
}
else return null;
}
};
};
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]);
}
}
@ChrisBaker97
Copy link
Author

Added default chunkSize of 100kb if none is specified and also changed the .get() method to return null (vice undefined) if there is no data present, to align with normal Cache Service behavior.

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