问题描述
我已经创建了一个服务工作者,该服务工作者先执行提取操作,然后立即将数据存储在缓存中。
self.addEventListener('install',async function(e) {
try {
const fileCache = await caches.open(CACHE_NAME);
await fileCache.addAll(FILES_TO_CACHE);
const dataCache = await caches.open(DATA_CACHE_NAME);
const dataFetchResponse = await fetch('/api/transaction');
return await dataCache.put('/api/transaction',dataFetchResponse);
} catch (error) {
console.log(error);
}
});
执行完此操作后,我将尝试使它能够测试自从上次获取数据以来已经有多长时间了,以确定是否需要更新数据。我的Transaction
模型在数据上添加了时间戳,因此理想情况下,我想针对当前时间测试最后一笔交易的时间戳,但是我不确定该怎么做。
我试图做cache.match()
,但是它没有返回匹配键的整个对象。我知道localStorage有一个.getItem()
方法,但没有看到类似的cache
方法。
对此有什么想法吗?
解决方法
弄清楚如何获取信息。您必须.match()
key
存储在缓存中的数据,由于它返回了一个Promise,因此您需要将其转换为.json()
对象。
async function getCachedData(cacheName,url) {
const cacheStorage = await caches.open(cacheName);
const cachedResponse = await cacheStorage.match(url); // Returns a promise w/ matched cache
if(!cachedResponse || !cachedResponse.ok) {return false}
console.log(await cachedResponse);
console.log(await cachedResponse.json()); // prints json object with value of key matched
return await cachedResponse.json();
};