From fe62cadd6fb4a7e49f7d59401fc74ae0411e32a7 Mon Sep 17 00:00:00 2001 From: Adam Soltys Date: Mon, 26 Aug 2024 21:17:43 -0700 Subject: typescript --- lib/notifications.ts | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 lib/notifications.ts (limited to 'lib/notifications.ts') diff --git a/lib/notifications.ts b/lib/notifications.ts new file mode 100644 index 00000000..af47a6d7 --- /dev/null +++ b/lib/notifications.ts @@ -0,0 +1,38 @@ +import config from "$config"; +import webpush from "web-push"; + +if (config.vapid) { + webpush.setVapidDetails( + config.vapid.url, + config.vapid.publicKey, + config.vapid.privateKey, + ); +} + +export const notify = async (user, payload) => { + try { + let { subscriptions } = user; + + if (subscriptions) { + let i = 0; + for (let subscription of subscriptions) { + i++; + try { + await webpush.sendNotification(subscription, payload); + } catch (e) { + if ( + e.body && + (e.body.includes("expired") || e.body.includes("No such")) + ) { + user.subscriptions.splice(i, 1); + await user.save(); + } else { + err("problem sending notification", e); + } + } + } + } + } catch (e) { + console.log("problem notifying", e); + } +}; -- cgit v1.2.3