Add Web Push warning notification backend
This commit is contained in:
43
lib/notification-api.ts
Normal file
43
lib/notification-api.ts
Normal 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));
|
||||
}
|
||||
Reference in New Issue
Block a user