如何在我的React应用程序中访问已注册的工作簿队列



我正在为我的PWA使用服务工作者内置的create-react应用程序。我使用workbox中的Queue类将失败的api调用添加到队列中。服务工作者的所有注册都在我的service-worker.ts文件中完成。

我的问题是:如何访问React组件中已经注册的队列?我想显示一个计数器,说明未被调用的api的数量。我不清楚我怎样才能做到这一点。

服务人员.ts

// add failed fetch requests to queue
const queue = new Queue('fetch-requests');
self.addEventListener('fetch', (event) => {
if (!self.navigator.onLine) {
const promiseChain = fetch(event.request.clone()).catch(() => {
if (event.request.method === 'POST' || event.request.method === 'PATCH') {
return queue.pushRequest({ request: event.request });
}
});
event.waitUntil(promiseChain);
}
});

应用程序.tsx

const App: React.FC = () => {
// how can I access the queue from here and do some stuff with it?
return <Router />;
};
export default App;

您的队列在indexedDB中存储为"工作簿后台同步";。所以,这只是一个查询商店的问题。参见以下示例

function getQueuesMeta() {
return new Promise(resolve => {
const connection = indexedDB.open("workbox-background-sync")
const res = []

connection.onsuccess = (event) => {
const db = event.target.result

try{
const tx = db.transaction(["requests"])
const reqIndex = tx.objectStore('requests').index('queueName')

reqIndex.openCursor().onsuccess = (e) => {
const cursor = e.target.result
let meta = {}
if (cursor) {
meta = {
// if you got meta, time to get it
timestamp: cursor.value.timestamp
}
if ('undefined' == typeof res[cursor.key]) {
res[cursor.key] = [meta]
} else {
res[cursor.key].push(meta)
}
cursor.continue()
} else {
resolve(res)
}
}
} catch (error){
console.log('no ‘request’ objectStore')
resolve(null)
}
}
})
}

最新更新