# All files / src/db/repositories/drizzle message.ts

100% Statements 23/23
100% Branches 22/22
100% Functions 10/10
100% Lines 23/23

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
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139

    145x

    46x
    46x

    46x

    46x

    3x

    3x

    3x
    2x

    1x

    5x
    4x

    1x

    2x

    2x

    2x

    6x

    6x
    1x

    5x

    2x

    2x
    1x

     /**
     * Drizzle Message Repository Adapter
     *
     * Implements MessageRepository interface using Drizzle ORM.
     */

    import { eq, and, desc } from 'drizzle-orm';
    import { nanoid } from 'nanoid';
    import type { DrizzleDatabase } from '../../index.js';
    import { messages, type Message } from '../../schema.js';
    import type {
      MessageRepository,
      CreateMessageData,
      UpdateMessageData,
      MessageParticipantType,
    } from '../message-repository.js';

    /**
     * Drizzle adapter for MessageRepository.
     *
     * Uses dependency injection for database instance,
     * enabling isolated test databases.
     */
    export class DrizzleMessageRepository implements MessageRepository {
      constructor(private db: DrizzleDatabase) {}

      async create(data: CreateMessageData): Promise<Message> {
        const id = nanoid();
        const now = new Date();

        const [created] = await this.db.insert(messages).values({
          id,
          senderType: data.senderType,
          senderId: data.senderId ?? null,
          recipientType: data.recipientType,
          recipientId: data.recipientId ?? null,
          type: data.type ?? 'info',
          content: data.content,
          requiresResponse: data.requiresResponse ?? false,
          status: data.status ?? 'pending',
          parentMessageId: data.parentMessageId ?? null,
          createdAt: now,
          updatedAt: now,
        }).returning();

        return created;
      }

      async findById(id: string): Promise<Message | null> {
        const result = await this.db
          .select()
          .from(messages)
          .where(eq(messages.id, id))
          .limit(1);

        return result[0] ?? null;
      }

      async findBySender(type: MessageParticipantType, id?: string): Promise<Message[]> {
        if (id) {
          return this.db
            .select()
            .from(messages)
            .where(and(eq(messages.senderType, type), eq(messages.senderId, id)))
            .orderBy(desc(messages.createdAt));
        }

        // For user sender (no id), find where senderType='user' and senderId is null
        return this.db
          .select()
          .from(messages)
          .where(eq(messages.senderType, type))
          .orderBy(desc(messages.createdAt));
      }

      async findByRecipient(type: MessageParticipantType, id?: string): Promise<Message[]> {
        if (id) {
          return this.db
            .select()
            .from(messages)
            .where(and(eq(messages.recipientType, type), eq(messages.recipientId, id)))
            .orderBy(desc(messages.createdAt));
        }

        // For user recipient (no id), find where recipientType='user' and recipientId is null
        return this.db
          .select()
          .from(messages)
          .where(eq(messages.recipientType, type))
          .orderBy(desc(messages.createdAt));
      }

      async findPendingForUser(): Promise<Message[]> {
        return this.db
          .select()
          .from(messages)
          .where(and(eq(messages.recipientType, 'user'), eq(messages.status, 'pending')))
          .orderBy(desc(messages.createdAt));
      }

      async findRequiringResponse(): Promise<Message[]> {
        return this.db
          .select()
          .from(messages)
          .where(and(eq(messages.requiresResponse, true), eq(messages.status, 'pending')))
          .orderBy(desc(messages.createdAt));
      }

      async findReplies(parentMessageId: string): Promise<Message[]> {
        return this.db
          .select()
          .from(messages)
          .where(eq(messages.parentMessageId, parentMessageId))
          .orderBy(desc(messages.createdAt));
      }

      async update(id: string, data: UpdateMessageData): Promise<Message> {
        const [updated] = await this.db
          .update(messages)
          .set({ ...data, updatedAt: new Date() })
          .where(eq(messages.id, id))
          .returning();

        if (!updated) {
          throw new Error(`Message not found: ${id}`);
        }

        return updated;
      }

      async delete(id: string): Promise<void> {
        const [deleted] = await this.db.delete(messages).where(eq(messages.id, id)).returning();

        if (!deleted) {
          throw new Error(`Message not found: ${id}`);
        }
      }
    }