Last active
June 24, 2018 18:04
-
-
Save Bajena/63d6d26245d20541c4150fbc9dc5cda0 to your computer and use it in GitHub Desktop.
Code.gs file with caching
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
//... | |
function getData(request) { | |
// ... | |
var startDate = request.dateRange.startDate; | |
var endDate = request.dateRange.endDate; | |
var cache = new DataCache(CacheService.getUserCache(), startDate, endDate); | |
var plays = null; | |
plays = fetchFromCache(cache); | |
if (!plays) { | |
plays = fetchFromApi(startDate, endDate); | |
setInCache(plays, cache); | |
} | |
return buildTabularData(plays, dataSchema); | |
} | |
function prepareSchema(request) { | |
// Prepare the schema for the fields requested. | |
var dataSchema = []; | |
var fixedSchema = getSchema().schema; | |
request.fields.forEach(function(field) { | |
for (var i = 0; i < fixedSchema.length; i++) { | |
if (fixedSchema[i].name == field.name) { | |
dataSchema.push(fixedSchema[i]); | |
break; | |
} | |
} | |
}); | |
return dataSchema; | |
} | |
function fetchFromCache(cache) { | |
var plays = null; | |
console.log('Trying to fetch from cache...'); | |
try { | |
var playsString = cache.get(); | |
plays = JSON.parse(playsString); | |
console.log('Fetched succesfully from cache', plays.length); | |
} catch (e) { | |
console.log('Error when fetching from cache:', e); | |
} | |
return plays; | |
} | |
function setInCache(plays, cache) { | |
console.log('Setting data to cache...'); | |
try { | |
cache.set(JSON.stringify(plays)); | |
} catch (e) { | |
console.log('Error when storing in cache', e); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment