[FIX] website_event_track: reuse fetch logic for prefetching urls

Before this commit, when prefetching urls if one of them fails, the
following are dropped.

This commit fixes it by handling each url seperately instead of sending
all of them to `cache.addAll()`. It also reuse the same logic as the
regular FetchEvent for consistency.

X-original-commit: 47fdfb8ae73ab79100fb83751ff0f132b4a5c628
Co-authored-by: Olivier Dony <odo@odoo.com>
This commit is contained in:
Pierre Paridans
2020-10-02 13:56:32 +00:00
co-authored by Olivier Dony
parent 65c65b6c19
commit 0e56f7ce7d
@@ -225,7 +225,7 @@ const matchCache = async (request) => {
* @param {FetchEvent} param0
* @returns {Promise<Response>}
*/
const processFetchEvent = async ({ request }) => {
const processFetchRequest = async ({ request }) => {
const requestCopy = request.clone();
let response;
try {
@@ -288,11 +288,17 @@ const processPendingRequests = async () => {
*/
const prefetchUrls = async (urls = []) => {
const cache = await caches.open(cacheName);
let urlsToCache = new Set(urls);
for (let url of urlsToCache) {
(await cache.match(url)) ? urlsToCache.delete(url) : undefined;
const uniqUrls = new Set(urls);
for (let url of uniqUrls) {
if (await cache.match(url)) {
continue;
}
try {
await processFetchRequest({ request: new Request(url) });
} catch (error) {
console.error(`fail to prefetch ${url} : ${error}`);
}
}
return cache.addAll([...urlsToCache]);
};
/**
@@ -327,7 +333,7 @@ const processMessage = (data) => {
};
self.addEventListener("fetch", (event) => {
event.respondWith(processFetchEvent(event));
event.respondWith(processFetchRequest(event));
});
self.addEventListener("sync", (event) => {