From 07d638b66c6a7dc1dc252d82cd9585f25c4cad4e Mon Sep 17 00:00:00 2001 From: Jeff Date: Sat, 12 Oct 2024 14:38:35 -0400 Subject: [PATCH] Send debug messages back to client --- app/worker.ts | 63 +++++++++++++++++++++++++++++++-------------------- 1 file changed, 38 insertions(+), 25 deletions(-) diff --git a/app/worker.ts b/app/worker.ts index 07ed7d9..254bb67 100644 --- a/app/worker.ts +++ b/app/worker.ts @@ -40,19 +40,43 @@ export default function start(self: ServiceWorkerGlobalScope) { // ) // }) - self.addEventListener("message", async function (event) { - if ( - "type" in event && - event.type === "subscribed" && - "subscription" in event - ) { - await event.waitUntil( - submitSubscription( - self.registration, - event.subscription as PushSubscription - ) - ) - } + async function sendMessage(message: any) { + const clients = await self.clients.matchAll() + + await Promise.all( + clients.map(async (client) => client.postMessage(message)) + ) + } + + self.addEventListener("message", function (event) { + const waitEvent = event as ExtendableEvent + waitEvent.waitUntil( + (async () => { + if ( + "type" in event && + event.type === "subscribed" && + "subscription" in event + ) { + try { + await event.waitUntil( + submitSubscription( + self.registration, + event.subscription as PushSubscription + ) + ) + } catch (e) { + await sendMessage({ + message: "Got error processing subscription", + error: (e as Error).toString(), + }) + } + } + + await sendMessage({ + message: "Processed subscription", + }) + })() + ) }) self.addEventListener("pushsubscriptionchange", function (event) { @@ -67,18 +91,7 @@ export default function start(self: ServiceWorkerGlobalScope) { existingSubscription ) - const clients = await self.clients.matchAll() - - await Promise.all( - clients.map(async (client) => - client.postMessage({ - subscription: - await self.registration.pushManager.getSubscription(), - event, - newSubscription, - }) - ) - ) + await sendMessage({ type: "sent subscription", newSubscription }) })() ) })