Feat/s3 storage #2
@@ -208,13 +208,27 @@ export class MessageService {
|
|||||||
membersBy.set(p.threadId, [...(membersBy.get(p.threadId) ?? []), name]);
|
membersBy.set(p.threadId, [...(membersBy.get(p.threadId) ?? []), name]);
|
||||||
}
|
}
|
||||||
|
|
||||||
const summaries = await Promise.all(
|
// Latest message per thread in ONE query (Postgres DISTINCT ON) instead of one findFirst
|
||||||
threads.map(async (t) => {
|
// per thread — a caller with many threads no longer fans out N parallel queries and
|
||||||
const last = await this.prisma.iiosInteraction.findFirst({
|
// exhausts the connection pool.
|
||||||
where: { threadId: t.id },
|
const lastRows =
|
||||||
orderBy: { occurredAt: 'desc' },
|
threads.length === 0
|
||||||
include: { parts: { where: { kind: 'TEXT' }, take: 1 } },
|
? []
|
||||||
});
|
: await this.prisma.$queryRaw<Array<{ threadId: string; occurredAt: Date; lastMessage: string | null }>>(Prisma.sql`
|
||||||
|
SELECT DISTINCT ON (i."threadId")
|
||||||
|
i."threadId" AS "threadId",
|
||||||
|
i."occurredAt" AS "occurredAt",
|
||||||
|
(SELECT p."bodyText" FROM "IiosMessagePart" p
|
||||||
|
WHERE p."interactionId" = i.id AND p.kind::text = 'TEXT'
|
||||||
|
ORDER BY p."partIndex" ASC LIMIT 1) AS "lastMessage"
|
||||||
|
FROM "IiosInteraction" i
|
||||||
|
WHERE i."threadId" IN (${Prisma.join(threads.map((t) => t.id))})
|
||||||
|
ORDER BY i."threadId", i."occurredAt" DESC
|
||||||
|
`);
|
||||||
|
const lastBy = new Map(lastRows.map((r) => [r.threadId, r]));
|
||||||
|
|
||||||
|
const summaries = threads.map((t) => {
|
||||||
|
const last = lastBy.get(t.id);
|
||||||
const members = membersBy.get(t.id) ?? [];
|
const members = membersBy.get(t.id) ?? [];
|
||||||
return {
|
return {
|
||||||
threadId: t.id,
|
threadId: t.id,
|
||||||
@@ -225,11 +239,10 @@ export class MessageService {
|
|||||||
participantCount: members.length,
|
participantCount: members.length,
|
||||||
unread: unreadBy.get(t.id) ?? 0,
|
unread: unreadBy.get(t.id) ?? 0,
|
||||||
muted: mutedBy.get(t.id) ?? false,
|
muted: mutedBy.get(t.id) ?? false,
|
||||||
lastMessage: last?.parts[0]?.bodyText ?? undefined,
|
lastMessage: last?.lastMessage ?? undefined,
|
||||||
lastAt: last?.occurredAt,
|
lastAt: last?.occurredAt,
|
||||||
};
|
};
|
||||||
}),
|
});
|
||||||
);
|
|
||||||
return summaries.sort((a, b) => (b.lastAt?.getTime() ?? 0) - (a.lastAt?.getTime() ?? 0));
|
return summaries.sort((a, b) => (b.lastAt?.getTime() ?? 0) - (a.lastAt?.getTime() ?? 0));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user