Add test push notification flow
This commit is contained in:
30
app/api/notifications/test/route.ts
Normal file
30
app/api/notifications/test/route.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { getPushSubscription, removePushSubscription } from "@/lib/push-store";
|
||||
import { isWebPushConfigured, sendTestNotification } from "@/lib/push-service";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
if (!isWebPushConfigured()) {
|
||||
return NextResponse.json({ error: "Web Push is not configured." }, { status: 503 });
|
||||
}
|
||||
|
||||
const body = await request.json().catch(() => null) as { endpoint?: unknown } | null;
|
||||
if (typeof body?.endpoint !== "string" || !body.endpoint) {
|
||||
return NextResponse.json({ error: "Invalid push subscription endpoint." }, { status: 400 });
|
||||
}
|
||||
|
||||
const subscription = getPushSubscription(body.endpoint);
|
||||
if (!subscription || !subscription.enabled) {
|
||||
return NextResponse.json({ error: "Push subscription was not found." }, { status: 404 });
|
||||
}
|
||||
|
||||
try {
|
||||
await sendTestNotification(subscription);
|
||||
return NextResponse.json({ ok: true });
|
||||
} catch (error) {
|
||||
const statusCode = typeof error === "object" && error !== null && "statusCode" in error ? Number(error.statusCode) : null;
|
||||
if (statusCode === 404 || statusCode === 410) removePushSubscription(subscription.endpoint);
|
||||
return NextResponse.json({ error: "Unable to send test notification." }, { status: 502 });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user