import type { Client, Notification } from "magicbell-js/user-client"; import { Collection } from "tinycoll"; import { isOK } from "../lib/response"; import type { RealtimeStore } from "./realtime-store"; type Options = { client: Client; socket: RealtimeStore; }; type Meta = { lastFetched: number; userId: string; }; export class NotificationStore extends Collection { #client: Client; #socket: RealtimeStore; #interval: ReturnType | null = null; #nextCursor: string | null = null; #hasMore = true; #fetching = false; #hasLoadedMore = false; #REFRESH_INTERVAL = 60_000; #CACHE_TTL = 10_000; constructor(options: Options) { super("notifications"); this.#client = options.client; this.#socket = options.socket; // realtime listener only inits in browsers if (typeof window === "undefined" || typeof document === "undefined") return; this.#socket.listen({}, () => { void this.#fetchPageOne({ force: true }); }); this.onReady(() => { this.#startPolling(); }); } #startPolling() { if (this.#interval) return; this.#interval = setInterval(() => this.#fetchPageOne({ force: true }), this.#REFRESH_INTERVAL); void this.#fetchPageOne({ force: true }); } stopPolling() { if (!this.#interval) return; clearInterval(this.#interval); this.#interval = null; } async #fetchPageOne(options: { force?: boolean; } = {}) { if (this.#fetching) return; const lastFetched = this.meta.get("lastFetched") || 0; if (!options.force && Date.now() - lastFetched <= this.#CACHE_TTL) return; this.#fetching = true; try { const { data, metadata, nextCursor } = await this.#fetchPage(null); if (isOK(metadata)) { this.meta.set("lastFetched", Date.now()); } if (!data) { if (!this.#hasLoadedMore) { this.#nextCursor = null; this.#hasMore = false; } return; } if (!this.#hasLoadedMore) { this.#nextCursor = nextCursor; this.#hasMore = Boolean(nextCursor); } } finally { this.#fetching = false; } } async fetchMore() { if (!this.#hasMore || !this.#nextCursor) return; if (this.#fetching) return; this.#fetching = true; try { const { data, nextCursor } = await this.#fetchPage(this.#nextCursor); if (!data) { this.#nextCursor = null; this.#hasMore = false; return; } this.#hasLoadedMore = true; this.#nextCursor = nextCursor; this.#hasMore = Boolean(nextCursor); } finally { this.#fetching = false; } } async #fetchPage(startingAfter: string | null) { const { data, metadata } = await this.#client.notifications.listNotifications(startingAfter ? { startingAfter } : {}); if (!data) return { data, metadata, nextCursor: null }; for (const row of data.data ?? []) { this.insert(row); } const next = data.links?.next; const nextCursor = next ? new URL(next).searchParams.get("starting_after") : null; return { data, metadata, nextCursor }; } markAsRead(id: string) { const current = this.findOne({ id })?.readAt || null; this.update({ id }, { $set: { readAt: new Date().toISOString() } }); this.#client.notifications.markNotificationRead(id).catch(() => { this.update({ id }, { $set: { readAt: current } }); }); } markAsUnread(id: string) { const current = this.findOne({ id })?.readAt || null; this.update({ id }, { $set: { readAt: null } }); this.#client.notifications.markNotificationUnread(id).catch(() => { this.update({ id }, { $set: { readAt: current } }); }); } markAllRead() { const now = new Date().toISOString(); const ids = this.find({ readAt: null }).toArray().map(x => x.id); this.update({ id: { $in: ids } }, { $set: { readAt: now } }); this.#client.notifications.markAllNotificationsRead().catch(() => { this.update({ id: { $in: ids } }, { $set: { readAt: null } }); }); } archive(id: string) { const current = this.findOne({ id })?.archivedAt || null; this.update({ id }, { $set: { archivedAt: new Date().toISOString() } }); this.#client.notifications.archiveNotification(id).catch(() => { this.update({ id }, { $set: { archivedAt: current } }); }); } }