workbox - Workbox 5.1.2 后台同步队列配置
问题描述
我最近从 Workbox 3.5.0 迁移到 Workbox 5.1.2
我正在通过 CDN 使用 Workbox SW
importScripts('https://storage.googleapis.com/workbox-cdn/releases/5.1.2/workbox-sw.js');
我已经更新了我的服务工作者文件以使用最新的插件类,并适当地重命名了这些类 - 一切都很好!
我遇到的唯一真正的问题/困惑是 backgroundSync 模块。我已阅读文档并在 Stackoverflow 和 Google 上搜索解决方案/建议,但找不到任何明确回答我的问题的内容。
我正在尝试将失败的请求添加到网络恢复后重试的队列。
workbox.routing.registerRoute(new RegExp('/\/php\/postPO.php/'),
new workbox.strategies.NetworkOnly({
plugins: [
new workbox.backgroundSync.BackgroundSyncPlugin('po-data-queue', {
maxRetentionTime: 24 * 60 * 2
})
]
}),
'POST'
);
const queue = new workbox.backgroundSync.Queue('po-data-queue-2');
self.addEventListener('fetch', (event) => {
const promiseChain = fetch(event.request.clone()).catch((err) => {
return queue.pushRequest({ request: event.request });
});
event.waitUntil(promiseChain);
});
我知道上面的代码不起作用,因为如果我给 2 个队列名称赋予相同的名称,则会引发关于使用唯一队列名称的错误。我是否需要这两个函数才能使用 backgroundSync 模块,或者是其中一个。另外,我需要自己创建 indexedDB 还是工作箱处理这个?使用 workbox 3.5.0 时,我创建了 indexedDB 并添加了失败的请求,如下所示(效果很好):
function createIndexedDB() {
if (!('indexedDB' in window)) {return null;}
return idb.open('pos-data-queue', 1, function(upgradeDb) {
if (!upgradeDb.objectStoreNames.contains('events')) {
const eventsOS = upgradeDb.createObjectStore('events', {keyPath: 'key', autoIncrement: true});
}
});
}
const dbPromise = createIndexedDB();
function saveEventDataLocally(events) {
console.log(events);
if (!('indexedDB' in window)) {return null;}
return dbPromise.then(db => {
const tx = db.transaction('events', 'readwrite');
const store = tx.objectStore('events');
return Promise.all(events.map(event => store.put(event)))
.catch((err) => {
console.log(err);
tx.abort();
throw Error('Events were not added to the store');
});
});
}
const bgSyncPlugin = new workbox.backgroundSync.Plugin('pos-data-queue');
const networkWithBackgroundSync = new workbox.strategies.NetworkOnly({
plugins: [bgSyncPlugin],
});
workbox.routing.registerRoute(
/\/php\/postPO.php/,
networkWithBackgroundSync,
'POST'
);
我无法理解这是如何工作的,任何帮助将不胜感激
解决方案
您不需要同时使用BackgroundSyncPlugin
和Queue
。每个实例都需要一个唯一的名称。IndexedDB 条目由 Workbox 本身管理。
在您的代码示例中,我在注册时看到了一个可疑空间(使正则表达式无效)BackgroundSyncPlugin
:
workbox.routing.registerRoute(new RegExp(' /\/php\/postPO.php/'),
^
也许你可以尝试:
workbox.routing.registerRoute(/\/php\/postPO\.php/,
new workbox.strategies.NetworkOnly({
plugins: [
new workbox.backgroundSync.BackgroundSyncPlugin('po-data-queue', {
maxRetentionTime: 2 * 24 * 60 // two days
})
]
}),
'POST'
);
以上内容适用于任何包含/php/postPO.php
. 你可以在这里测试它。
此处的官方文档展示了一些示例以及如何测试后台同步是否实际工作。
推荐阅读
- powerapps - 如何在 PowerApps 中将颜色设置为全局变量?
- redis - 使用 ReJSON 从 redis 获取元素范围
- excel - 在工作表函数中使用表引用
- python - 在保持受限布局的同时将轴重新添加到 matplotlib 图形的正确方法是什么?
- image - Docker:无法从损坏的拉取中删除中间图像
- javascript - 我可以把它变成 1 个 switch case 而不是很多 if else 语句
- html - 响应式表中断
- r - 使用 R 整理数据
- php - 在一个 foreach 中比较两个数组的所有值
- angular - angular.json 样式导入和生产构建文件