我试图了解Service Worker,并尝试实现一个解决方案,使我可以脱机工作,保存数据并在联机后将其同步到服务器。
我遵循了本指南:Handle POST/PUT requests in offline applications using service workers
除该指南外,我还动态保存了缓存,这意味着API GET请求在联机时会与数据一起保存在缓存中。有了这些数据,我正在渲染页面。但是,我有两个问题。
当我离线保存时,索引数据库得到更新,但缓存保持不变。这意味着,如果我仍处于脱机状态时重新加载页面,则更改是不可见的(因为它是从缓存加载的)。我可以基于indexedDB POST以某种方式更新缓存吗?
将数据保存到索引数据库的功能:
function savePostRequests(url, payload) {
// get object_store and save our payload inside it
var request = getObjectStore(FOLDER_NAME, 'readwrite').add({
url: url,
payload: payload,
method: 'PUT'
});
...
}
第二个问题是,当在线时,它会发出GET请求并将数据设置为状态。 GET之后,服务工作者将脱机时所做的更改发布到服务器。通常,当我执行发布请求并成功后,我会更新状态。
但是,当Service Worker同步时,它不会设置状态。这意味着GET中的数据未显示最新数据(POST同步后)。如果重新加载页面(在同步后),我将获得最新数据。
索引到数据库的数据库发布到服务器:
function sendPostToServer() {
var savedRequests = []
var req = getObjectStore(FOLDER_NAME).openCursor()
req.onsuccess = async function (event) {
var cursor = event.target.result
if (cursor) {
// Keep moving the cursor forward and collecting saved equests.
savedRequests.push(cursor.value);
cursor.continue();
} else {
// At this point, we have collected all the post requests in indexedb.
for (let savedRequest of savedRequests) {
// send them to the server one after the other
var requestUrl = savedRequest.url
var payload = JSON.stringify(savedRequest.payload)
var method = savedRequest.method
var headers = {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
fetch(requestUrl, {
headers: headers,
method: method,
body: payload
}).then(function (response) {
console.log('server response', response)
if (response.status < 400) {
// remove it from the IndexedDB.
getObjectStore(FOLDER_NAME, 'readwrite').delete(savedRequest.id);
}
}).catch(function (error) {
console.error('Send to Server failed:', error);
throw error;
})
}
}
}
}
所以...
如果我做错了什么,或者可以改善某些地方,请告诉我,因为我仍在学习服务人员。