Add Web Push warning notification backend
This commit is contained in:
51
lib/push-store.ts
Normal file
51
lib/push-store.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import type { WarningPushSubscription } from "@/types/notifications";
|
||||
|
||||
interface PushStore {
|
||||
subscriptions: Map<string, WarningPushSubscription>;
|
||||
sentWarningIds: Map<string, Set<string>>;
|
||||
}
|
||||
|
||||
const globalStore = globalThis as typeof globalThis & { __wtrPushStore?: PushStore };
|
||||
|
||||
function getStore() {
|
||||
if (!globalStore.__wtrPushStore) {
|
||||
globalStore.__wtrPushStore = {
|
||||
subscriptions: new Map(),
|
||||
sentWarningIds: new Map(),
|
||||
};
|
||||
}
|
||||
return globalStore.__wtrPushStore;
|
||||
}
|
||||
|
||||
export function upsertPushSubscription(subscription: WarningPushSubscription) {
|
||||
getStore().subscriptions.set(subscription.endpoint, subscription);
|
||||
}
|
||||
|
||||
export function removePushSubscription(endpoint: string) {
|
||||
const store = getStore();
|
||||
store.subscriptions.delete(endpoint);
|
||||
store.sentWarningIds.delete(endpoint);
|
||||
}
|
||||
|
||||
export function getPushSubscriptions() {
|
||||
return Array.from(getStore().subscriptions.values());
|
||||
}
|
||||
|
||||
export function hasSentWarning(endpoint: string, warningId: string) {
|
||||
return getStore().sentWarningIds.get(endpoint)?.has(warningId) ?? false;
|
||||
}
|
||||
|
||||
export function markWarningSent(endpoint: string, warningId: string) {
|
||||
const store = getStore();
|
||||
const sentIds = store.sentWarningIds.get(endpoint) ?? new Set<string>();
|
||||
sentIds.add(warningId);
|
||||
store.sentWarningIds.set(endpoint, sentIds);
|
||||
}
|
||||
|
||||
export function pruneSentWarnings(activeWarningIds: Set<string>) {
|
||||
getStore().sentWarningIds.forEach((sentIds) => {
|
||||
sentIds.forEach((warningId) => {
|
||||
if (!activeWarningIds.has(warningId)) sentIds.delete(warningId);
|
||||
});
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user