Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion jest.setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ jest.mock("react-hotkeys-hook", () => ({
useHotkeys: () => {}
}));

jest.mock("@/lib/ratelimit", () => {
jest.mock("@/lib/ratelimit/ratelimit", () => {
const createLimiter = () => ({
limit: jest.fn().mockResolvedValue({
success: true,
Expand Down
30 changes: 23 additions & 7 deletions src/app/api/doubts/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,11 +162,6 @@
conditions.push(eq(doubtsTable.isSolved, "unsolved"));
}

const replyCountSql =
sql<number>`coalesce((SELECT count(*) FROM ${repliesTable} WHERE ${repliesTable.doubtId} = ${doubtsTable.id}), 0)`.mapWith(
Number,
);

const [totalCountRow] = await db
.select({ count: count() })
.from(doubtsTable)
Expand All @@ -176,7 +171,6 @@
const query = db
.select({
...getTableColumns(doubtsTable),
replyCount: replyCountSql,
})
.from(doubtsTable);

Expand All @@ -190,7 +184,10 @@
if (sort === "popular") {
orderByFields.push(desc(doubtsTable.likes));
} else if (sort === "most-replied") {
orderByFields.push(desc(replyCountSql));
// Needed here only to sort correctly at the DB level before paging.
// Not selected as a column, so it costs nothing for any other sort mode.
const replyCountOrderSql = sql`coalesce((SELECT count(*) FROM ${repliesTable} WHERE ${repliesTable.doubtId} = ${doubtsTable.id}), 0)`;
orderByFields.push(desc(replyCountOrderSql));
}
orderByFields.push(desc(doubtsTable.createdAt));

Expand All @@ -200,6 +197,25 @@
.limit(limit)
.offset(offset);

// Batch-fetch reply counts for just the returned page (max `limit` ids)
// instead of running a correlated subquery per row in the SELECT.
if (doubts.length > 0) {
const replyCountRows = await db
.select({ doubtId: repliesTable.doubtId, count: count() })
.from(repliesTable)
.where(inArray(repliesTable.doubtId, doubts.map((d: any) => d.id)))
.groupBy(repliesTable.doubtId);

const replyCountMap = new Map(
replyCountRows.map((r: any) => [r.doubtId, Number(r.count)]),
);

doubts = doubts.map((doubt: any) => ({
...doubt,
replyCount: replyCountMap.get(doubt.id) ?? 0,
}));
}

if (email && doubts.length > 0) {
const userLikes = await db
.select({ doubtId: likesTable.doubtId })
Expand Down Expand Up @@ -238,7 +254,7 @@
.innerJoin(tagsTable, eq(doubtTagsTable.tagId, tagsTable.id))
.where(inArray(doubtTagsTable.doubtId, doubts.map((d: any) => d.id)));

const tagsByDoubt = tagRows.reduce<

Check failure on line 257 in src/app/api/doubts/route.ts

View workflow job for this annotation

GitHub Actions / TypeScript Check

Untyped function calls may not accept type arguments.
Record<number, { id: number; name: string; normalizedName: string }[]>
>((acc, row) => {
acc[row.doubtId] = acc[row.doubtId] || [];
Expand Down Expand Up @@ -417,7 +433,7 @@
for (const name of normalizedTags) {
const match = existingTagsMap.get(name);
if (match) {
savedTags.push(match);

Check failure on line 436 in src/app/api/doubts/route.ts

View workflow job for this annotation

GitHub Actions / TypeScript Check

Argument of type 'unknown' is not assignable to parameter of type '{ id: number; name: string; createdAt: Date; classroomId: number; normalizedName: string; createdByEmail: string; }'.
} else {
tagsToInsert.push({
name: name.replace(/\b\w/g, (char) => char.toUpperCase()),
Expand Down
Loading