Skip to content

Instantly share code, notes, and snippets.

@Bajena
Last active June 24, 2018 18:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Bajena/63d6d26245d20541c4150fbc9dc5cda0 to your computer and use it in GitHub Desktop.
Save Bajena/63d6d26245d20541c4150fbc9dc5cda0 to your computer and use it in GitHub Desktop.
Code.gs file with caching
//...
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