/** * In-Memory Implementation: InMemoryNotificationRepository * * Provides an in-memory storage implementation for notifications. */ import { Notification } from '../../domain/entities/Notification'; import type { INotificationRepository } from '../../domain/repositories/INotificationRepository'; import type { NotificationType } from '../../domain/types/NotificationTypes'; export class InMemoryNotificationRepository implements INotificationRepository { private notifications: Map = new Map(); constructor(initialNotifications: Notification[] = []) { initialNotifications.forEach(notification => { this.notifications.set(notification.id, notification); }); } async findById(id: string): Promise { return this.notifications.get(id) || null; } async findByRecipientId(recipientId: string): Promise { return Array.from(this.notifications.values()) .filter(n => n.recipientId === recipientId) .sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime()); } async findUnreadByRecipientId(recipientId: string): Promise { return Array.from(this.notifications.values()) .filter(n => n.recipientId === recipientId && n.isUnread()) .sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime()); } async findByRecipientIdAndType(recipientId: string, type: NotificationType): Promise { return Array.from(this.notifications.values()) .filter(n => n.recipientId === recipientId && n.type === type) .sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime()); } async countUnreadByRecipientId(recipientId: string): Promise { return Array.from(this.notifications.values()) .filter(n => n.recipientId === recipientId && n.isUnread()) .length; } async create(notification: Notification): Promise { if (this.notifications.has(notification.id)) { throw new Error(`Notification with ID ${notification.id} already exists`); } this.notifications.set(notification.id, notification); } async update(notification: Notification): Promise { if (!this.notifications.has(notification.id)) { throw new Error(`Notification with ID ${notification.id} not found`); } this.notifications.set(notification.id, notification); } async delete(id: string): Promise { this.notifications.delete(id); } async deleteAllByRecipientId(recipientId: string): Promise { const toDelete = Array.from(this.notifications.values()) .filter(n => n.recipientId === recipientId) .map(n => n.id); toDelete.forEach(id => this.notifications.delete(id)); } async markAllAsReadByRecipientId(recipientId: string): Promise { const toUpdate = Array.from(this.notifications.values()) .filter(n => n.recipientId === recipientId && n.isUnread()); toUpdate.forEach(n => { const updated = n.markAsRead(); this.notifications.set(updated.id, updated); }); } }