【发布时间】:2019-06-09 14:44:47
【问题描述】:
我尝试通过 service-worker 劫持特定的 GraphQL-Request 以伪造来自我的 IndexedDB 中数据的响应,但我收到一个错误,表明该事件已得到响应。提取适用于缓存文件,如果提取的数据不在缓存中,它将使用网络。如果没有网络,将有一个离线回退。我如何编排我的承诺,我还可以劫持对我的 GraphQL API 和特定查询(操作名称)的请求,因为我似乎搞砸了异步 event.respondWith 调用?
self.addEventListener('fetch', function (event) {
if (event.request.url === __GRAPHQL_URL__) {
event.request.clone().json().then(({operationName, variables}) => {
switch (operationName) {
case 'getOfflineFacilities':
//when a fetch is matching there will be the error
event.respondWith(serveOfflineFacilities());
}
});
}else{
event.respondWith(
caches.match(event.request).then(function (response) {
console.log("cache or network fallback");
return response || fetch(event.request);
}).catch(function () {
console.log("offline fallback");
return caches.match('/index.html');
})
);
}
});
当 GraphQL 查询命中 __GRAPHQL_URL__ 和我的 operationName
时出错sw.js:41 Uncaught (in promise) DOMException: Failed to execute 'respondWith' on 'FetchEvent': The event has already been responded to.
【问题讨论】:
-
是唯一的
fetch事件监听器吗? -
请注意,您永远不会处理
event.request.clone().json()承诺的失败 -
是的,只有它一个
-
我的 switch case 中的 event.respondWith 遥不可及。你知道锄头来解决这个问题,不会早点回复吗?
-
我上面代码中的那个。我的问题是我的 switch case 中的所有内容都已得到响应
标签: javascript es6-promise service-worker fetch-api