| 1 | import { and, asc, eq, inArray } from 'drizzle-orm' |
| 2 | import { db } |
| 3 | import { members, threadMessages |
| 4 | |
| 5 | const getThreads = async |
| 6 | const rows = |
| 7 | .select() |
| 8 | .from(threads) |
| 9 | .where( |
| 10 | and(eq(threads |
| 11 | ) |
| 12 | .orderBy(asc(threads |
| 13 | |
| 14 | const threadIds = |
| 15 | if (threadIds.length |
| 16 | return [] |
| 17 | } |
| 18 | |
| 19 | const messages = |
| 20 | .select({ |
| 21 | id: threadMessages.id |
| 22 | threadId: threadMessages.threadId |
| 23 | authorMemberId: threadMessages.authorMemberId |
| 24 | authorName: users.name |
| 25 | authorImage: users.image |
| 26 | body: threadMessages.body |
| 27 | createdAt: threadMessages.createdAt |
| 28 | }) |
| 29 | .from(threadMessages) |
| 30 | .leftJoin(members, |
| 31 | .leftJoin(users, |
| 32 | .where(inArray(threadMessages |
| 33 | .orderBy(asc(threadMessages |
| 34 | |
| 35 | const messagesByThread = |
| 36 | for (const msg |
| 37 | const list = |
| 38 | list.push(msg |
| 39 | messagesByThread.set(msg |
| 40 | } |
| 41 | |
| 42 | // Get creator info |
| 43 | const creatorIds = |
| 44 | .map((t) |
| 45 | .filter((id) |
| 46 | const creators = |
| 47 | creatorIds.length > 0 |
| 48 | ? await db |
| 49 | .select({ |
| 50 | memberId: members.id |
| 51 | name: users.name |
| 52 | image: users.image |
| 53 | }) |
| 54 | .from(members) |
| 55 | .leftJoin(users, |
| 56 | .where(inArray(members |
| 57 | : [] |
| 58 | |
| 59 | const creatorMap = |
| 60 | |
| 61 | return rows.map |
| 62 | const creator = |
| 63 | ? creatorMap.get( |
| 64 | : null |
| 65 | return { |
| 66 | id: t.id |
| 67 | selectedText: t.selectedText |
| 68 | status: t.status |
| 69 | createdByMemberId: t.createdByMemberId |
| 70 | createdByName: creator?.name |
| 71 | createdByImage: creator?.image |
| 72 | messages: messagesByThread.get |
| 73 | createdAt: t.createdAt |
| 74 | } |
| 75 | }) |
| 76 | } |
| 77 | |
| 78 | export const threadService = |
| 79 | getThreads, |
| 80 | } |