Add Web Push warning notification backend

This commit is contained in:
zv
2026-06-11 19:17:13 +02:00
parent 531e678922
commit 054d75b1f4
15 changed files with 645 additions and 36 deletions

43
lib/notification-api.ts Normal file
View File

@@ -0,0 +1,43 @@
import type { Language } from "@/lib/i18n";
import type { Province } from "@/types/province";
interface VapidKeyResponse {
configured: boolean;
publicKey: string | null;
}
export async function fetchVapidPublicKey(signal?: AbortSignal) {
const response = await fetch("/api/notifications/vapid-key", { signal });
if (!response.ok) throw new Error("Unable to load Web Push configuration.");
return response.json() as Promise<VapidKeyResponse>;
}
export async function savePushSubscription(subscription: PushSubscription, province: Province, language: Language) {
const response = await fetch("/api/notifications/subscriptions", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
subscription: subscription.toJSON(),
province,
language,
enabled: true,
}),
});
if (!response.ok) throw new Error("Unable to save push subscription.");
}
export async function deletePushSubscription(endpoint: string) {
const response = await fetch("/api/notifications/subscriptions", {
method: "DELETE",
headers: { "content-type": "application/json" },
body: JSON.stringify({ endpoint }),
});
if (!response.ok) throw new Error("Unable to delete push subscription.");
}
export function decodeBase64UrlKey(value: string) {
const padding = "=".repeat((4 - (value.length % 4)) % 4);
const base64 = `${value}${padding}`.replace(/-/g, "+").replace(/_/g, "/");
const raw = window.atob(base64);
return Uint8Array.from(raw, (character) => character.charCodeAt(0));
}