owltide/server/web-push.ts
Hornwitser abdcc83eb9 Refactor subscription format
Place the actual push subscription data into a push property on the
subscription so that other properties can be added to it.
2025-03-07 12:37:47 +01:00

46 lines
1.3 KiB
TypeScript

import webPush from "web-push";
import { readSubscriptions, writeSubscriptions } from "~/server/database";
webPush.setVapidDetails(
"mailto:webmaster@hornwitser.no",
process.env.NUXT_PUBLIC_VAPID_PUBLIC_KEY!,
process.env.NUXT_VAPID_PRIVATE_KEY!,
)
export async function sendPush(title: string, body: string) {
const payload = JSON.stringify({ title, body });
const subscriptions = await readSubscriptions();
console.log(`Sending "${payload}" to ${subscriptions.length} subscribers`);
const removeIndexes = [];
for (let index = 0; index < subscriptions.length; index += 1) {
const subscription = subscriptions[index];
if (subscription.type !== "push")
continue;
try {
await webPush.sendNotification(
subscription.push as webPush.PushSubscription,
payload,
{
TTL: 3600,
urgency: "high",
}
)
} catch (err: any) {
if (err?.statusCode === 410) {
removeIndexes.push(index);
} else {
console.error("Received error sending push notice:", err.message, err?.statusCode)
console.error(err);
}
}
}
if (removeIndexes.length) {
console.log(`Removing indexes ${removeIndexes} from subscriptions`)
removeIndexes.reverse();
for (const index of removeIndexes) {
subscriptions.splice(index, 1);
}
await writeSubscriptions(subscriptions);
}
console.log("Push notices sent");
}