Files
wtr/lib/push-store.ts

84 lines
2.7 KiB
TypeScript

import type { WarningPushSubscription } from "@/types/notifications";
interface PushStore {
subscriptions: Map<string, WarningPushSubscription>;
sentWarningIds: Map<string, Set<string>>;
sentMorningBriefDates: Map<string, Set<string>>;
sentTomorrowBriefDates: 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(),
sentMorningBriefDates: new Map(),
sentTomorrowBriefDates: 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);
store.sentMorningBriefDates.delete(endpoint);
store.sentTomorrowBriefDates.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);
});
});
}
export function hasSentMorningBrief(endpoint: string, dateKey: string) {
return getStore().sentMorningBriefDates.get(endpoint)?.has(dateKey) ?? false;
}
export function markMorningBriefSent(endpoint: string, dateKey: string) {
const store = getStore();
const sentDates = store.sentMorningBriefDates.get(endpoint) ?? new Set<string>();
sentDates.add(dateKey);
store.sentMorningBriefDates.set(endpoint, sentDates);
}
export function hasSentTomorrowBrief(endpoint: string, dateKey: string) {
return getStore().sentTomorrowBriefDates.get(endpoint)?.has(dateKey) ?? false;
}
export function markTomorrowBriefSent(endpoint: string, dateKey: string) {
const store = getStore();
const sentDates = store.sentTomorrowBriefDates.get(endpoint) ?? new Set<string>();
sentDates.add(dateKey);
store.sentTomorrowBriefDates.set(endpoint, sentDates);
}