Move the code dealing with saving and loading data to server/database to gather it all up into one place.
43 lines
1.3 KiB
TypeScript
43 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];
|
|
try {
|
|
await webPush.sendNotification(
|
|
subscription as webPush.PushSubscription,
|
|
payload,
|
|
{
|
|
TTL: 3600,
|
|
urgency: "high",
|
|
}
|
|
)
|
|
} catch (err: any) {
|
|
console.error("Received error sending push notice:", err.message, err?.statusCode)
|
|
console.error(err);
|
|
if (err?.statusCode >= 400 && err?.statusCode < 500) {
|
|
removeIndexes.push(index)
|
|
}
|
|
}
|
|
}
|
|
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");
|
|
}
|