Skip to content

Commit

Permalink
rm throw from getAvailableServiceWorker
Browse files Browse the repository at this point in the history
* There are cases where getAvailableServiceWorker returning `null` is ok
and it safe to move on so the following was done.
   - Removed the throw
   - Added a warning log etnry
   - Added null handling where this method is being called.
  • Loading branch information
jkasten2 committed Feb 18, 2021
1 parent 42bec5f commit 57f60b2
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 4 deletions.
6 changes: 3 additions & 3 deletions src/helpers/page/ServiceWorkerUtilHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ export default class ServiceWorkerUtilHelper {
}

// A ServiceWorkerRegistration will have a ServiceWorker in 1 of 3 states, get which ever is available.
static getAvailableServiceWorker(registration: ServiceWorkerRegistration): ServiceWorker {
static getAvailableServiceWorker(registration: ServiceWorkerRegistration): ServiceWorker | null {
const availableWorker = registration.active || registration.installing || registration.waiting;
// This should never throw unless ServiceWorkerRegistration is pointing to a worker that is completely gone.
// This never be null unless ServiceWorkerRegistration is pointing to a worker that is completely gone.
if (!availableWorker) {
throw new Error("Could not find an available ServiceWorker instance!");
Log.warn("Could not find an available ServiceWorker instance!");
}
return availableWorker;
}
Expand Down
8 changes: 7 additions & 1 deletion src/libraries/WorkerMessenger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,8 +152,14 @@ export class WorkerMessenger {
return;
}

const availableWorker = ServiceWorkerUtilHelper.getAvailableServiceWorker(workerRegistration);
if (!availableWorker) {
Log.error("`[Worker Messenger] [Page -> SW] Could not get ServiceWorker to postMessage!");
return;
}

// The postMessage payload will still arrive at the SW even if it isn't active yet.
ServiceWorkerUtilHelper.getAvailableServiceWorker(workerRegistration).postMessage({
availableWorker.postMessage({
command: command,
payload: payload
});
Expand Down
4 changes: 4 additions & 0 deletions src/managers/ServiceWorkerManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,10 @@ export class ServiceWorkerManager {
// Get the file name of the active ServiceWorker
private static activeSwFileName(workerRegistration: ServiceWorkerRegistration): string | null {
const serviceWorker = ServiceWorkerUtilHelper.getAvailableServiceWorker(workerRegistration);
if (!serviceWorker) {
return null;
}

const workerScriptPath = new URL(serviceWorker.scriptURL).pathname;
const swFileName = new Path(workerScriptPath).getFileName();

Expand Down

0 comments on commit 57f60b2

Please sign in to comment.