ST-cmovs7jgr: lib/push-server.ts met sendPushToUser + stale-cleanup
Server-only push-lib met VAPID feature-gate, send naar alle subscriptions van een user, en automatische cleanup bij 404/410. Unit tests: success-pad, 410 verwijdert sub, 404 verwijdert sub, andere errors loggen zonder delete. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
parent
2f5ea553bc
commit
880a3097af
2 changed files with 143 additions and 0 deletions
64
lib/push-server.ts
Normal file
64
lib/push-server.ts
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
import 'server-only'
|
||||
|
||||
import webpush from 'web-push'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { env } from '@/lib/env'
|
||||
|
||||
export type PushPayload = {
|
||||
title: string
|
||||
body: string
|
||||
url: string
|
||||
tag?: string
|
||||
}
|
||||
|
||||
const vapidReady =
|
||||
!!env.NEXT_PUBLIC_VAPID_PUBLIC_KEY &&
|
||||
!!env.VAPID_PRIVATE_KEY &&
|
||||
!!env.VAPID_SUBJECT
|
||||
|
||||
if (vapidReady) {
|
||||
webpush.setVapidDetails(
|
||||
env.VAPID_SUBJECT!,
|
||||
env.NEXT_PUBLIC_VAPID_PUBLIC_KEY!,
|
||||
env.VAPID_PRIVATE_KEY!,
|
||||
)
|
||||
}
|
||||
|
||||
export const enabled = vapidReady
|
||||
|
||||
export async function sendPushToUser(userId: string, payload: PushPayload): Promise<void> {
|
||||
if (!enabled) {
|
||||
console.warn('[push-server] VAPID not configured — skipping push for user', userId)
|
||||
return
|
||||
}
|
||||
|
||||
const subs = await prisma.pushSubscription.findMany({ where: { user_id: userId } })
|
||||
await Promise.allSettled(subs.map((sub) => sendOne(sub, payload)))
|
||||
}
|
||||
|
||||
async function sendOne(
|
||||
sub: { id: string; endpoint: string; p256dh: string; auth: string },
|
||||
payload: PushPayload,
|
||||
): Promise<void> {
|
||||
try {
|
||||
await webpush.sendNotification(
|
||||
{ endpoint: sub.endpoint, keys: { p256dh: sub.p256dh, auth: sub.auth } },
|
||||
JSON.stringify(payload),
|
||||
)
|
||||
await prisma.pushSubscription.update({
|
||||
where: { id: sub.id },
|
||||
data: { last_used_at: new Date() },
|
||||
})
|
||||
} catch (err: unknown) {
|
||||
const status = (err as { statusCode?: number }).statusCode
|
||||
if (status === 404 || status === 410) {
|
||||
try {
|
||||
await prisma.pushSubscription.delete({ where: { id: sub.id } })
|
||||
} catch {
|
||||
// already deleted by a concurrent request — ignore
|
||||
}
|
||||
} else {
|
||||
console.error('[push-server] sendNotification error for endpoint', sub.endpoint, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue