83 lines
2.3 KiB
TypeScript
83 lines
2.3 KiB
TypeScript
/**
|
|
* Notification reader service - detects new notifications in IndexedDB
|
|
* This service is separate from the Service Worker that populates notifications
|
|
*/
|
|
|
|
import { notificationService } from './notificationService'
|
|
import type { Notification } from './notificationService'
|
|
|
|
class NotificationReader {
|
|
private lastReadTime: number = 0
|
|
private subscribers: Array<(notifications: Notification[]) => void> = []
|
|
|
|
/**
|
|
* Subscribe to notification updates
|
|
*/
|
|
subscribe(callback: (notifications: Notification[]) => void): () => void {
|
|
this.subscribers.push(callback)
|
|
|
|
// Return unsubscribe function
|
|
return () => {
|
|
const index = this.subscribers.indexOf(callback)
|
|
if (index > -1) {
|
|
this.subscribers.splice(index, 1)
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Notify subscribers of new notifications
|
|
*/
|
|
private notifySubscribers(notifications: Notification[]): void {
|
|
this.subscribers.forEach((callback) => {
|
|
try {
|
|
callback(notifications)
|
|
} catch (error) {
|
|
console.error('[NotificationReader] Error in subscriber callback:', error)
|
|
}
|
|
})
|
|
}
|
|
|
|
/**
|
|
* Read notifications from IndexedDB
|
|
*/
|
|
async readNotifications(limit: number = 100): Promise<Notification[]> {
|
|
try {
|
|
const notifications = await notificationService.getAllNotifications(limit)
|
|
this.lastReadTime = Date.now()
|
|
this.notifySubscribers(notifications)
|
|
return notifications
|
|
} catch (error) {
|
|
console.error('[NotificationReader] Error reading notifications:', error)
|
|
return []
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get unread notifications count
|
|
*/
|
|
async getUnreadCount(): Promise<number> {
|
|
try {
|
|
return await notificationService.getUnreadCount()
|
|
} catch (error) {
|
|
console.error('[NotificationReader] Error getting unread count:', error)
|
|
return 0
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get new notifications since last read
|
|
*/
|
|
async getNewNotifications(since: number = this.lastReadTime): Promise<Notification[]> {
|
|
try {
|
|
const allNotifications = await notificationService.getAllNotifications(1000)
|
|
return allNotifications.filter((n) => n.timestamp > since)
|
|
} catch (error) {
|
|
console.error('[NotificationReader] Error getting new notifications:', error)
|
|
return []
|
|
}
|
|
}
|
|
}
|
|
|
|
export const notificationReader = new NotificationReader()
|