All files / src/infrastructure/database/repositories prisma-notification.repository.ts

100% Statements 9/9
100% Branches 2/2
100% Functions 6/6
100% Lines 9/9

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71                                  3x                           23x     3x 3x       1x 1x       18x     18x       10x                                      
import { PrismaClient } from '../../../generated/prisma/client';
import { NotificationRepository } from '../../../application/notification/notification-repository';
import { Notification, NotificationType } from '../../../domain/notification/notification';
 
interface NotificationRow {
  id: string;
  userId: string;
  babyId: string;
  type: string;
  referenceId: string;
  title: string;
  message: string;
  readAt: Date | null;
  createdAt: Date;
}
 
function toDomain(row: NotificationRow): Notification {
  return Notification.restore({
    id: row.id,
    userId: row.userId,
    babyId: row.babyId,
    type: row.type as NotificationType,
    referenceId: row.referenceId,
    title: row.title,
    message: row.message,
    readAt: row.readAt,
    createdAt: row.createdAt,
  });
}
 
export class PrismaNotificationRepository implements NotificationRepository {
  constructor(private readonly prisma: PrismaClient) {}
 
  async findById(id: string): Promise<Notification | null> {
    const row = await this.prisma.notification.findUnique({ where: { id } });
    return row ? toDomain(row) : null;
  }
 
  async findAllByUserId(userId: string): Promise<Notification[]> {
    const rows = await this.prisma.notification.findMany({ where: { userId }, orderBy: { createdAt: 'desc' } });
    return rows.map(toDomain);
  }
 
  async existsForTrigger(babyId: string, type: NotificationType, referenceId: string): Promise<boolean> {
    const row = await this.prisma.notification.findUnique({
      where: { babyId_type_referenceId: { babyId, type, referenceId } },
    });
    return row !== null;
  }
 
  async save(notification: Notification): Promise<void> {
    await this.prisma.notification.upsert({
      where: { id: notification.id },
      create: {
        id: notification.id,
        userId: notification.userId,
        babyId: notification.babyId,
        type: notification.type,
        referenceId: notification.referenceId,
        title: notification.title,
        message: notification.message,
        readAt: notification.readAt,
        createdAt: notification.createdAt,
      },
      update: {
        readAt: notification.readAt,
      },
    });
  }
}