From cd87e95173d4320ae4de2eca7f26248290c61ffa Mon Sep 17 00:00:00 2001 From: Shailesh Baldaniya Date: Thu, 24 Sep 2020 21:55:55 +0530 Subject: [PATCH] Fix SW for API calls by responding with network response first (#413) * Fix SW for API calls by responding with network response first * Update package-lock.json * Improve implementation --- package-lock.json | 6 ++---- public/sw.js | 10 +++++++--- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/package-lock.json b/package-lock.json index aebe7f4239c1..167443b645a2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5154,8 +5154,7 @@ "preact-i18nline": "^2.0.0", "preact-router": "^3.2.1", "query-string": "^6.13.1", - "sanitize-html": "^1.27.2", - "whatwg-fetch": "^3.4.0" + "sanitize-html": "^1.27.2" }, "dependencies": { "@rocket.chat/ui-kit": { @@ -5178,8 +5177,7 @@ "whatwg-fetch": { "version": "3.4.1", "resolved": "https://registry.npmjs.org/whatwg-fetch/-/whatwg-fetch-3.4.1.tgz", - "integrity": "sha512-sofZVzE1wKwO+EYPbWfiwzaKovWiZXf4coEzjGP9b2GBVgQRLQUZ2QcuPpQExGDAW5GItpEm6Tl4OU5mywnAoQ==", - "dev": true + "integrity": "sha512-sofZVzE1wKwO+EYPbWfiwzaKovWiZXf4coEzjGP9b2GBVgQRLQUZ2QcuPpQExGDAW5GItpEm6Tl4OU5mywnAoQ==" } } }, diff --git a/public/sw.js b/public/sw.js index ff8568875bb3..3906abe320fa 100644 --- a/public/sw.js +++ b/public/sw.js @@ -25,7 +25,7 @@ function handleAvatar(request, response) { caches.open(version).then((cache) => cache.put(new Request(url), clonedResponse)); } -const fetchFromNetwork = (event) => { +const fetchFromNetwork = (event, cached) => { const requestToFetch = event.request.clone(); return fetch(requestToFetch, { cache: 'reload' }).then((response) => { const clonedResponse = response.clone(); @@ -57,7 +57,7 @@ const fetchFromNetwork = (event) => { } return response; }).catch(() => { - if (hasHash(event.request.url)) { return caches.match(event.request.url); } + if (cached) { return cached; } // If the request URL hasn't been served from cache and isn't sockjs we suppose it's HTML if (!/\/sockjs\//.test(event.request.url)) { return caches.match(HTMLToCache); } // Only for sockjs @@ -106,9 +106,13 @@ self.addEventListener('fetch', (event) => { const resourceType = cached.headers.get('content-type'); // We only return non css/js/html cached response e.g images if (!hasHash(event.request.url) && !/text\/html/.test(resourceType)) { + // If API call try to respond with network response first + if (/\/api\//.test(event.request.url)) { + return fetchFromNetwork(event, cached); + } // Refresh resources which are not(sound or assets) if (!/sounds/.test(event.request.url) && !/assets/.test(event.request.url) && !/font/.test(event.request.url)) { - fetchFromNetwork(event); + fetchFromNetwork(event, cached); } return cached; }