【发布时间】:2021-04-12 09:33:03
【问题描述】:
我正在尝试让下面的代码(Google 表格的自定义函数)将 API 查询的结果无限期地存储在缓存中。
// The cache key for "New York" and "new york " should be same
const md5 = (key = '') => {
const code = key.toLowerCase().replace(/\s/g, '');
return Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, key)
.map((char) => (char + 256).toString(16).slice(-2))
.join('');
};
const getCache = (key) => {
return CacheService.getDocumentCache().get(md5(key));
};
// Store the results for 6 hours
const setCache = (key, value) => {
const expirationInSeconds = 6 * 60 * 60;
CacheService.getDocumentCache().put(md5(key), value, expirationInSeconds);
};
const GOOGLEMAPS_DISTANCE = (origin, destination, mode = 'driving') => {
const key = ['distance', origin, destination, mode].join(',');
// Is result in the internal cache?
const value = getCache(key);
// If yes, serve the cached result
if (value !== null) return value;
const { routes: [data] = [] } = Maps.newDirectionFinder()
.setOrigin(origin)
.setDestination(destination)
.setMode(mode)
.getDirections();
if (!data) {
GOOGLEMAPS_DISTANCE;
}
const { legs: [{ distance: { text: distance } } = {}] = [] } = data;
// Store the result in internal cache for future
setCache(key, distance);
return distance;
};
使用 Google Maps API,该函数能够返回 Google 表格中指定的两个位置之间的距离,并将结果保存在缓存中 6 小时。如果新输入的位置之前已经被检索和缓存过,则将检索缓存的结果,否则将发送新的 API 查询。
根据Class Cache上的Google's documentation,使用put调用,结果最多只能在内部缓存中存储6小时:
expirationInSeconds:
整数:
值在缓存中保留的最长时间,以秒为单位。最小值为 1 秒,最大值为 21600 秒(6 小时)。
不过,我读到了 Place IDs (documentation),这可能是 6 小时限制的一种解决方法。
来自Places API Policies 文档:
请注意,用于唯一标识地点的地点 ID 不受缓存限制。因此,您可以无限期地存储地点 ID 值。地点 ID 在地点 API 响应的
place_id字段中返回。
我发现的另一种可能的解决方法是在Google Properties Service Documentation 中使用Properties,但我似乎无法在代码中实现它。
如果有人愿意回复并帮助我,我将不胜感激。
【问题讨论】:
标签: javascript google-apps-script google-sheets google-api google-places-api