073170c96a
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
39 lines
1.0 KiB
TypeScript
39 lines
1.0 KiB
TypeScript
import webpush from "web-push";
|
|
import { db, pushSubscriptions, eq } from "@epicure/db";
|
|
|
|
let vapidInitialized = false;
|
|
function ensureVapid() {
|
|
if (vapidInitialized) return;
|
|
const pub = process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY;
|
|
const priv = process.env.VAPID_PRIVATE_KEY;
|
|
if (!pub || !priv) throw new Error("VAPID keys not configured");
|
|
webpush.setVapidDetails("mailto:contact@epicure.app", pub, priv);
|
|
vapidInitialized = true;
|
|
}
|
|
|
|
export async function sendPushNotification(
|
|
userId: string,
|
|
notification: { title: string; body: string; url?: string }
|
|
): Promise<void> {
|
|
ensureVapid();
|
|
const subs = await db
|
|
.select()
|
|
.from(pushSubscriptions)
|
|
.where(eq(pushSubscriptions.userId, userId));
|
|
|
|
const payload = JSON.stringify({
|
|
title: notification.title,
|
|
body: notification.body,
|
|
url: notification.url ?? "/",
|
|
});
|
|
|
|
await Promise.allSettled(
|
|
subs.map((sub) =>
|
|
webpush.sendNotification(
|
|
{ endpoint: sub.endpoint, keys: { p256dh: sub.p256dh, auth: sub.auth } },
|
|
payload
|
|
)
|
|
)
|
|
);
|
|
}
|