From d95898005cd7d8e9501a3b51bd066dcd8686df55 Mon Sep 17 00:00:00 2001 From: Dobromir Popov Date: Tue, 7 May 2024 11:59:41 +0300 Subject: [PATCH] push subscriptions managment --- components/PwaManager.tsx | 47 ++++++++++++++++++++------------------ pages/api/notify.ts | 48 +++++++++++++++++++++++++++++++++------ worker/index.js | 2 +- 3 files changed, 67 insertions(+), 30 deletions(-) diff --git a/components/PwaManager.tsx b/components/PwaManager.tsx index a7e3f5d..6da931b 100644 --- a/components/PwaManager.tsx +++ b/components/PwaManager.tsx @@ -128,29 +128,32 @@ function PwaManager() { try { e.preventDefault(); - await subscription.unsubscribe(); - // Call your API to delete or invalidate subscription data on server - setSubscription(null); - setIsSubscribed(false); - if (session?.user?.id != null) { - await fetch(`/api/notify`, - { - method: 'DELETE', - headers: { - 'Content-Type': 'application/json' - }, - body: JSON.stringify({ id: session?.user.id }), - } - ).then(response => { - if (!response.ok) { - throw new Error('Failed to delete subscription data on server.'); - } - else { - console.log('Subscription data deleted on server.'); - } - }); + if (subscription) { + await subscription.unsubscribe(); + // Call your API to delete or invalidate subscription data on server + setSubscription(null); + setIsSubscribed(false); + if (session?.user?.id != null) { + await fetch(`/api/notify`, + { + method: 'DELETE', + headers: { + 'Content-Type': 'application/json' + }, + //send the current subscription to be removed + body: JSON.stringify({ id: session.user.id, subscriptionId: subscription.endpoint }) + } + ).then(response => { + if (!response.ok) { + throw new Error('Failed to delete subscription data on server.'); + } + else { + console.log('Subscription data deleted on server.'); + } + }); + } + console.log('Web push unsubscribed!'); } - console.log('Web push unsubscribed!'); } catch (error) { console.error('Error unsubscribing from notifications:', error); } diff --git a/pages/api/notify.ts b/pages/api/notify.ts index 0aee668..44aafce 100644 --- a/pages/api/notify.ts +++ b/pages/api/notify.ts @@ -35,11 +35,26 @@ const Notification = async (req, res) => { // publisher.pushSubscription = subscription const prisma = common.getPrismaClient(); const { subscription, id } = req.body - const publisher = await prisma.publisher.update({ + const publisher = await prisma.publisher.findUnique({ where: { id }, - data: { pushSubscription: subscription } - }) + select: { pushSubscription: true } + }); + + let subscriptions = Array.isArray(publisher.pushSubscription) ? publisher.pushSubscription : (publisher.pushSubscription ? [publisher.pushSubscription] : []); + const index = subscriptions.findIndex(sub => sub.endpoint === subscription.endpoint); + + if (index !== -1) { + subscriptions[index] = subscription; // Update existing subscription + } else { + subscriptions.push(subscription); // Add new subscription + } + + await prisma.publisher.update({ + where: { id }, + data: { pushSubscription: subscriptions } + }); console.log('Subscription for publisher', id, 'updated:', subscription) + res.send({ subs: subscriptions.length }) res.statusCode = 200 res.end() } @@ -47,12 +62,31 @@ const Notification = async (req, res) => { // remove the subscription object from the database // publisher.pushSubscription = null const prisma = common.getPrismaClient(); - const { id } = req.body - const publisher = await prisma.publisher.update({ + const { subscriptionId, id } = req.body; + + const publisher = await prisma.publisher.findUnique({ where: { id }, - data: { pushSubscription: null } - }) + select: { pushSubscription: true } + }); + + let subscriptions = Array.isArray(publisher.pushSubscription) ? publisher.pushSubscription : (publisher.pushSubscription ? [publisher.pushSubscription] : []); + try { + subscriptions = subscriptions.filter(sub => sub.endpoint !== subscriptionId); + + await prisma.publisher.update({ + where: { id }, + data: { pushSubscription: subscriptions } + }); + } catch (e) { + console.log(e) + await prisma.publisher.update({ + where: { id }, + data: { pushSubscription: null } + }); + } + console.log('Subscription for publisher', id, 'deleted') + res.send({ subs: subscriptions.length }) res.statusCode = 200 res.end() } diff --git a/worker/index.js b/worker/index.js index d119920..9f5ff7b 100644 --- a/worker/index.js +++ b/worker/index.js @@ -31,7 +31,7 @@ self.addEventListener('push', function (event) { registration.showNotification(data.title, { body: data.message, icon: '/favicon.ico', - actions: [...data.actions, { action: 'close', title: 'Close', icon: 'fa fa-times' }], + actions: [{ action: 'close', title: 'Close', icon: 'fa fa-times' }], data: data.url, }) )