From dbac266d236c0556a8c65bb582dd3b947d764244 Mon Sep 17 00:00:00 2001 From: MuslemRahimi Date: Sun, 2 Feb 2025 19:39:26 +0100 Subject: [PATCH] update push notification --- src/routes/+page.svelte | 1 - .../api/sendPushSubscription/+server.ts | 59 +++++++++++++++++++ src/service-worker.ts | 3 +- 3 files changed, 61 insertions(+), 2 deletions(-) create mode 100644 src/routes/api/sendPushSubscription/+server.ts diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte index be5c8830..252ba728 100644 --- a/src/routes/+page.svelte +++ b/src/routes/+page.svelte @@ -62,7 +62,6 @@ description="Stocknear has everything you need to analyze stocks with help of AI, including detailed financial data, statistics, news and charts." image="" /> -/>
{ + const { pb, apiKey } = locals; + + const { title, body, key } = await request?.json(); + + if (apiKey === key) { + + try { + + console.log(title, body) + + // Get all push subscriptions + const subscriptions = await pb.collection('pushSubscription').getFullList({ + sort: '-created' + }); + + // Send notifications to all subscriptions + const sendNotifications = subscriptions?.map(async (subRecord) => { + try { + const subscriptionData = subRecord.subscription?.subscription; + await webPush.sendNotification( + subscriptionData, // Ensure correct format + body + ); + } catch (error: any) { + console.error('Error sending notification:', error); + + // Delete invalid subscriptions (410 means "Gone") + if (error.statusCode === 410) { + await pb.collection('pushSubscription').delete(subRecord.id); + } + } + }); + + await Promise.all(sendNotifications); + + return new Response(JSON.stringify({ success: true, message: `Notifications sent to ${subscriptions.length} devices` })); + } catch (error: any) { + console.error('Error sending notifications:', error); + return new Response(JSON.stringify({ success: false, error: error.message }, { status: 500 })); + } + + } else { + console.log('api key wrong') + } + +}; diff --git a/src/service-worker.ts b/src/service-worker.ts index ab1fee43..f6719a26 100644 --- a/src/service-worker.ts +++ b/src/service-worker.ts @@ -85,7 +85,8 @@ self.addEventListener('push', function (event: any) { const registration = (self as any).registration as ServiceWorkerRegistration; event.waitUntil( registration.showNotification('Stocknear', { - body: payload + body: payload, + icon: "/pwa-192x192.png", }) ); } as EventListener); \ No newline at end of file