message.repository.ts76 lines, 2.2 KB
| 1 | import { randomUUID } from 'node:crypto'; |
| 2 | |
| 3 | import { type WithId, type Document, ObjectId } from 'mongodb'; |
| 4 | |
| 5 | import type { Message, MessageListOptions } from '@/types/message'; |
| 6 | |
| 7 | import { getMongoClient } from '@/clients/mongo.client'; |
| 8 | |
| 9 | const MESSAGES_COLLECTION = 'messages'; |
| 10 | |
| 11 | const toMessage = (doc: WithId<Document>): Message => ({ |
| 12 | id: String(doc._id), |
| 13 | conversationId: String(doc.conversationId), |
| 14 | senderId: String(doc.senderId), |
| 15 | body: String(doc.body), |
| 16 | createdAt: new Date(doc.createdAt as string | number | Date), |
| 17 | reactions: Array.isArray(doc.reactions) |
| 18 | ? doc.reactions.map((r: WithId<Document>) => ({ |
| 19 | emoji: String(r.emoji), |
| 20 | userId: String(r.userId), |
| 21 | createdAt: new Date(r.createdAt as string | number | Date), |
| 22 | })) |
| 23 | : [], |
| 24 | }); |
| 25 | |
| 26 | export const messageRepository = { |
| 27 | async create(conversationId: string, senderId: string, body: string): Promise<Message> { |
| 28 | const client = await getMongoClient(); |
| 29 | const db = client.db(); |
| 30 | const collection = db.collection(MESSAGES_COLLECTION); |
| 31 | const now = new Date(); |
| 32 | const document = { |
| 33 | _id: randomUUID(), |
| 34 | conversationId, |
| 35 | senderId, |
| 36 | body, |
| 37 | createdAt: now, |
| 38 | }; |
| 39 | |
| 40 | await collection.insertOne(document as unknown as Document); |
| 41 | |
| 42 | return toMessage(document as unknown as WithId<Document>); |
| 43 | }, |
| 44 | |
| 45 | async findByConversation( |
| 46 | conversationId: string, |
| 47 | options: MessageListOptions = {}, |
| 48 | ): Promise<Message[]> { |
| 49 | const client = await getMongoClient(); |
| 50 | const db = client.db(); |
| 51 | const query: Record<string, unknown> = { |
| 52 | conversationId, |
| 53 | }; |
| 54 | if (options.after) { |
| 55 | query.createdAt = { $gt: options.after }; |
| 56 | } |
| 57 | |
| 58 | const cursor = db |
| 59 | .collection(MESSAGES_COLLECTION) |
| 60 | .find(query) |
| 61 | .sort({ createdAt: -1 }) |
| 62 | .limit(options.limit ?? 50); |
| 63 | |
| 64 | const messages = await cursor.toArray(); |
| 65 | return messages.map((doc) => toMessage(doc)); |
| 66 | }, |
| 67 | |
| 68 | async findById(messageId: string): Promise<Message | null> { |
| 69 | const client = await getMongoClient(); |
| 70 | const db = client.db(); |
| 71 | const doc = await db |
| 72 | .collection(MESSAGES_COLLECTION) |
| 73 | .findOne({ _id: messageId } as unknown as Document); |
| 74 | return doc ? toMessage(doc) : null; |
| 75 | }, |
| 76 | }; |