56 lines
1.6 KiB
TypeScript
56 lines
1.6 KiB
TypeScript
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 getPushSubscription(endpoint: string) {
|
|
return getStore().subscriptions.get(endpoint) ?? null;
|
|
}
|
|
|
|
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);
|
|
});
|
|
});
|
|
}
|