【发布时间】:2018-02-10 19:40:41
【问题描述】:
在编写要在电子表格单元格中使用的自定义函数时,工作表的默认行为是在编辑时重新计算,即添加列或行将导致自定义函数更新。
这是一个问题,如果自定义函数调用付费 API 并使用积分,用户将自动消耗 API 积分。
我想不出办法来防止这种情况发生,所以我决定使用UserCache 将结果缓存任意 25 分钟,并在用户碰巧重复相同的函数调用时将其返回给用户.它绝对不是防弹的,但我想它总比没有好。显然是cache can hold 10mb,但这是正确的方法吗?我可以做一些更聪明的事情吗?
var _ROOT = {
cache : CacheService.getUserCache(),
cacheDefaultTime: 1500,
// Step 1 -- Construct a unique name for function call storage using the
// function name and arguments passed to the function
// example: function getPaidApi(1,2,3) becomes "getPaidApi123"
stringifyFunctionArguments : function(functionName,argumentsPassed) {
var argstring = ''
for (var i = 0; i < argumentsPassed.length; i++) {
argstring += argumentsPassed[i]
}
return functionName+argstring
},
//Step 2 -- when a user calls a function that uses a paid api, we want to
//cache the results for 25 minutes
addToCache : function (encoded, returnedValues) {
var values = {
returnValues : returnedValues
}
Logger.log(encoded)
this.cache.put(encoded, JSON.stringify(values), this.cacheDefaultTime)
}
//Step 3 -- if the user repeats the exact same function call with the same
//arguments, we give them the cached result
//this way, we don't consume API credits as easily.
checkCache : function(encoded) {
var cached = this.cache.get(encoded);
try {
cached = JSON.parse(cached)
return cached.returnValues
} catch (e) {
return false;
}
}
}
【问题讨论】:
标签: caching google-apps-script google-sheets custom-function