159 lines
5.3 KiB
TypeScript
159 lines
5.3 KiB
TypeScript
import { Injectable } from '@nestjs/common';
|
|
import { InjectDrizzle } from '@nestjs/drizzle';
|
|
import { UNREAD_COUNT_MAX } from '@repo/contracts';
|
|
import { and, eq, exists, gt, ne, sql, type SQL } from 'drizzle-orm';
|
|
import type { Database } from '../db/database';
|
|
import {
|
|
conversation,
|
|
conversationMember,
|
|
conversationRead,
|
|
message,
|
|
realmMember,
|
|
} from '../db/schema';
|
|
|
|
/**
|
|
* How far people have read, and what that leaves unread. Unread means
|
|
* messages from other people that are newer than the reader's marker or,
|
|
* for someone who has no marker yet, that came after they joined.
|
|
*/
|
|
@Injectable()
|
|
export class ReadsRepository {
|
|
constructor(@InjectDrizzle() private readonly db: Database) {}
|
|
|
|
/** Unread counts of the direct and group chats a user is in, by chat id. */
|
|
async countsForChats(userId: string): Promise<Map<string, number>> {
|
|
const rows = await this.db
|
|
.select({
|
|
conversationId: conversationMember.conversationId,
|
|
unread: unreadCount(
|
|
userId,
|
|
conversationMember.conversationId,
|
|
conversationMember.joinedAt,
|
|
),
|
|
})
|
|
.from(conversationMember)
|
|
.leftJoin(
|
|
conversationRead,
|
|
and(
|
|
eq(
|
|
conversationRead.conversationId,
|
|
conversationMember.conversationId,
|
|
),
|
|
eq(conversationRead.userId, conversationMember.userId),
|
|
),
|
|
)
|
|
.where(eq(conversationMember.userId, userId));
|
|
return new Map(rows.map((row) => [row.conversationId, row.unread]));
|
|
}
|
|
|
|
/** Unread counts of a realm's cauldrons for one of its members, by id. */
|
|
async countsForCauldrons(
|
|
userId: string,
|
|
realmId: string,
|
|
): Promise<Map<string, number>> {
|
|
const rows = await this.db
|
|
.select({
|
|
conversationId: conversation.id,
|
|
unread: unreadCount(userId, conversation.id, realmMember.joinedAt),
|
|
})
|
|
.from(conversation)
|
|
.innerJoin(
|
|
realmMember,
|
|
and(
|
|
eq(realmMember.realmId, conversation.realmId),
|
|
eq(realmMember.userId, userId),
|
|
),
|
|
)
|
|
.leftJoin(
|
|
conversationRead,
|
|
and(
|
|
eq(conversationRead.conversationId, conversation.id),
|
|
eq(conversationRead.userId, userId),
|
|
),
|
|
)
|
|
.where(eq(conversation.realmId, realmId));
|
|
return new Map(rows.map((row) => [row.conversationId, row.unread]));
|
|
}
|
|
|
|
/** The realms a user is in that have something unread in any cauldron. */
|
|
async realmsWithUnread(userId: string): Promise<Set<string>> {
|
|
const unreadMessage = this.db
|
|
.select({ one: sql`1` })
|
|
.from(conversation)
|
|
.innerJoin(message, eq(message.conversationId, conversation.id))
|
|
.leftJoin(
|
|
conversationRead,
|
|
and(
|
|
eq(conversationRead.conversationId, conversation.id),
|
|
eq(conversationRead.userId, userId),
|
|
),
|
|
)
|
|
.where(
|
|
and(
|
|
eq(conversation.realmId, realmMember.realmId),
|
|
isUnread(userId, realmMember.joinedAt),
|
|
),
|
|
);
|
|
const rows = await this.db
|
|
.select({ realmId: realmMember.realmId })
|
|
.from(realmMember)
|
|
.where(and(eq(realmMember.userId, userId), exists(unreadMessage)));
|
|
return new Set(rows.map((row) => row.realmId));
|
|
}
|
|
|
|
/**
|
|
* Moves a reader's marker to a message, never backwards, and answers with
|
|
* how many messages from other people came after where it now stands.
|
|
*/
|
|
async mark(
|
|
userId: string,
|
|
conversationId: string,
|
|
messageId: string,
|
|
): Promise<number> {
|
|
const [marker] = await this.db
|
|
.insert(conversationRead)
|
|
.values({ userId, conversationId, lastReadMessageId: messageId })
|
|
.onConflictDoUpdate({
|
|
target: [conversationRead.userId, conversationRead.conversationId],
|
|
set: {
|
|
lastReadMessageId: sql`greatest(${conversationRead.lastReadMessageId}, excluded.last_read_message_id)`,
|
|
updatedAt: sql`now()`,
|
|
},
|
|
})
|
|
.returning({ messageId: conversationRead.lastReadMessageId });
|
|
const newer = await this.db
|
|
.select({ id: message.id })
|
|
.from(message)
|
|
.where(
|
|
and(
|
|
eq(message.conversationId, conversationId),
|
|
ne(message.authorId, userId),
|
|
gt(message.id, marker.messageId),
|
|
),
|
|
)
|
|
.limit(UNREAD_COUNT_MAX);
|
|
return newer.length;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Whether a message row is unread by the user. For queries that join
|
|
* `conversation_read` (the user's marker, if any) next to `message`.
|
|
*/
|
|
function isUnread(userId: string, joinedAt: SQL | typeof realmMember.joinedAt) {
|
|
return sql`${message.authorId} <> ${userId} and case when ${conversationRead.lastReadMessageId} is not null then ${message.id} > ${conversationRead.lastReadMessageId} else ${message.createdAt} > ${joinedAt} end`;
|
|
}
|
|
|
|
/**
|
|
* A column counting a conversation's unread messages, up to the limit. For
|
|
* queries that join `conversation_read`, so they name every column in full.
|
|
*/
|
|
function unreadCount(
|
|
userId: string,
|
|
conversationId:
|
|
typeof conversation.id | typeof conversationMember.conversationId,
|
|
joinedAt: typeof realmMember.joinedAt | typeof conversationMember.joinedAt,
|
|
) {
|
|
return sql<number>`(select count(*)::int from (select 1 from ${message} where ${message.conversationId} = ${conversationId} and ${isUnread(userId, joinedAt as typeof realmMember.joinedAt)} limit ${UNREAD_COUNT_MAX}) as unread)`;
|
|
}
|