Workbox 5.1.2 backgroundSync 队列配置

Workbox 5.1.2 backgroundSync Queue configuration

我最近从 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 模块。 我已通读文档并在 Whosebug 和 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'
);

我无法理解这是如何工作的,任何帮助将不胜感激

您不需要同时使用 BackgroundSyncPluginQueue。每个实例都需要一个唯一的名称。 IndexedDB 条目由 Workbox 本身管理。

在您的代码示例中,我在注册 BackgroundSyncPlugin 时看到一个可疑的 space(使正则表达式无效):

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 的 URL。你可以测试一下here.

官方文档 here 展示了一些示例以及如何测试后台同步是否实际工作。