feat(cards): Phase ε.4 — Card list + discussions on /d/<slug>

- DiscussionService.countsForDeck: bulk count (visible) comments per
  card-content-hash for one deck. Mounted at GET
  /v1/decks/:slug/discussion-counts so the public deck page can
  render comment badges without N+1 fetches.
- <DeckCardList> on /d/<slug>: lists the latest version's cards,
  renders a one-line preview + "💬 N" badge, and expands the
  inline <CardDiscussions> on click. Anonymous visitors see counts;
  posting requires auth (CardDiscussions already gates that).
This commit is contained in:
Till JS 2026-05-07 22:46:47 +02:00
parent a8ddb6dea4
commit 46fefd5cc4
5 changed files with 145 additions and 1 deletions

View file

@ -23,6 +23,11 @@ export function createDiscussionRoutes(service: DiscussionService) {
return c.json(list);
});
router.get('/decks/:slug/discussion-counts', async (c) => {
const counts = await service.countsForDeck(c.req.param('slug'));
return c.json(counts);
});
router.post('/cards/:contentHash/discussions', async (c) => {
const user = requireUser(c.get('user'));
const parsed = postSchema.safeParse(await c.req.json().catch(() => ({})));

View file

@ -9,7 +9,7 @@
* if we want full nesting later it's already there.
*/
import { and, asc, eq } from 'drizzle-orm';
import { and, asc, eq, sql } from 'drizzle-orm';
import type { Database } from '../db/connection';
import { cardDiscussions, publicDecks } from '../db/schema';
import { ForbiddenError, NotFoundError } from '../lib/errors';
@ -52,6 +52,31 @@ export class DiscussionService {
return row;
}
/**
* Bulk count of (visible) comments per card-content-hash for one
* deck powers the "Karten" overview on the public deck page so
* we don't fan out one request per card.
*/
async countsForDeck(deckSlug: string): Promise<Record<string, number>> {
const deck = await this.db.query.publicDecks.findFirst({
where: eq(publicDecks.slug, deckSlug),
});
if (!deck) throw new NotFoundError('Deck not found');
const rows = await this.db
.select({
contentHash: cardDiscussions.cardContentHash,
count: sql<number>`count(*)::int`.as('count'),
})
.from(cardDiscussions)
.where(and(eq(cardDiscussions.deckId, deck.id), eq(cardDiscussions.hidden, false)))
.groupBy(cardDiscussions.cardContentHash);
const out: Record<string, number> = {};
for (const r of rows) out[r.contentHash] = r.count;
return out;
}
async listForCard(cardContentHash: string) {
const rows = await this.db
.select()