Phase 3: Domain-Modell + Decks/Cards/Reviews-CRUD

Domain (@cards/domain):
- zod-Schemas SSOT für Deck, Card, Review, StudySession, FsrsSettings,
  Tools (cards.create + cards.search Input/Output)
- CardType-Discriminated-Union: MVP basic+basic-reverse, Future-Set
  (cloze, type-in, image-occlusion, audio, multiple-choice) für
  Schema-stable-Migration vorbereitet
- validateFieldsForType() Pure-Function pro CardType
- FSRS-Adapter über ts-fsrs v5.3.2: newReview, gradeReview,
  subIndexCount, toFsrsCard/fromFsrsCard ISO↔Date-Roundtrip
- Encryption-Hinweis: reviews bleiben PLAINTEXT (Scheduler quert
  täglich `due <= now`, siehe Lessons §3)

Drizzle-Schemas (apps/api/src/db/schema, alles in pgSchema('cards')):
- decks, cards, card_tags, reviews (PK card_id+sub_index), study_sessions,
  tags (deck-skopiert), media_refs (verweist auf mana-media), import_jobs
- _schema.ts-Pattern um Zirkular-Imports zu vermeiden (Lesson aus
  mana-share/-events während F-0)
- Hot-Path-Index reviews_user_due_idx für Scheduler-Queries

Routes (apps/api/src/routes):
- POST/GET/PATCH/DELETE /api/v1/decks (Deck-CRUD)
- POST/GET/PATCH/DELETE /api/v1/cards (Card-CRUD mit Auto-Reviews-Init:
  beim Card-Insert werden N Reviews via subIndexCount(type) angelegt,
  in einer Transaktion)
- GET /api/v1/reviews/due (Hot-Path, optional deck_id-Filter, Limit 500)
- POST /api/v1/reviews/:cardId/:subIndex/grade (FSRS-State-Transition,
  per-Deck FSRS-Settings)

Auth: Stub-Middleware liest X-User-Id-Header (Phase 2 ersetzt durch
@mana/shared-hono authMiddleware mit JWKS-Cache).

Tests (vitest, Hono app.request()):
- @cards/domain: fsrs.test.ts (newReview, gradeReview Roundtrip,
  Rating-Mapping), schemas.test.ts (zod-strict-Variants, Field-Type-
  Validation, hex-Color)
- apps/api: decks.test.ts + cards.test.ts + reviews.test.ts —
  Auth-Gate + Input-Validation. Volle DB-Integrationstests folgen mit
  pg-mem oder testcontainers in späterer Phase.

Cleanup: types.ts entfernt, zod-Schemas sind SSOT (z.infer für Types).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Till 2026-05-08 14:21:54 +02:00
parent 8605b1b517
commit 45a47e0ffd
31 changed files with 1897 additions and 106 deletions

View file

@ -0,0 +1,98 @@
import { describe, it, expect } from 'vitest';
import { Hono } from 'hono';
import { cardsRouter } from '../src/routes/cards.ts';
import type { CardsDb } from '../src/db/connection.ts';
/**
* Routen-Tests ohne echte DB. Drizzle-Aufrufe werden durch eine
* minimale Stub-DB ersetzt, die nur die Validations-Pfade abdeckt.
*/
function buildApp() {
const app = new Hono();
const stub = {
select: () => ({
from: () => ({
where: () => ({ limit: () => [] }),
}),
}),
};
app.route('/api/v1/cards', cardsRouter({ db: stub as unknown as CardsDb }));
return { app };
}
describe('cardsRouter — auth-gate', () => {
it('GET ohne X-User-Id ist 401', async () => {
const { app } = buildApp();
const res = await app.request('/api/v1/cards');
expect(res.status).toBe(401);
});
});
describe('cardsRouter — Input-Validation', () => {
it('POST mit leerem Body ist 422', async () => {
const { app } = buildApp();
const res = await app.request('/api/v1/cards', {
method: 'POST',
headers: { 'X-User-Id': 'u-1', 'Content-Type': 'application/json' },
body: '{}',
});
expect(res.status).toBe(422);
});
it('POST mit basic-Card ohne back-Feld ist 422', async () => {
const { app } = buildApp();
const res = await app.request('/api/v1/cards', {
method: 'POST',
headers: { 'X-User-Id': 'u-1', 'Content-Type': 'application/json' },
body: JSON.stringify({
deck_id: 'd-1',
type: 'basic',
fields: { front: 'Q' },
}),
});
expect(res.status).toBe(422);
});
it('POST mit unknown CardType ist 422', async () => {
const { app } = buildApp();
const res = await app.request('/api/v1/cards', {
method: 'POST',
headers: { 'X-User-Id': 'u-1', 'Content-Type': 'application/json' },
body: JSON.stringify({
deck_id: 'd-1',
type: 'cloze',
fields: { text: 'x' },
}),
});
expect(res.status).toBe(422);
});
it('PATCH mit extra prop ist 422', async () => {
const { app } = buildApp();
const res = await app.request('/api/v1/cards/c-1', {
method: 'PATCH',
headers: { 'X-User-Id': 'u-1', 'Content-Type': 'application/json' },
body: JSON.stringify({ fields: { front: 'X' }, leak: 'bad' }),
});
expect(res.status).toBe(422);
});
it('POST mit gültigem basic-Card erreicht Deck-Lookup (404 bei stub)', async () => {
const { app } = buildApp();
const res = await app.request('/api/v1/cards', {
method: 'POST',
headers: { 'X-User-Id': 'u-1', 'Content-Type': 'application/json' },
body: JSON.stringify({
deck_id: 'd-1',
type: 'basic',
fields: { front: 'Q', back: 'A' },
}),
});
// Stub-DB gibt empty array → Deck-Not-Found-Pfad
expect(res.status).toBe(404);
const body = (await res.json()) as { error: string };
expect(body.error).toBe('deck_not_found');
});
});

View file

@ -0,0 +1,164 @@
import { describe, it, expect } from 'vitest';
import { Hono } from 'hono';
import { decksRouter } from '../src/routes/decks.ts';
import type { CardsDb } from '../src/db/connection.ts';
/**
* Routen-Tests ohne echte DB. Wir mocken die paar Drizzle-Methoden, die
* der Decks-Router nutzt, mit einem winzigen In-Memory-Store.
*
* Echte Integrations-Tests (gegen postgres/pg-mem) folgen in einer späteren
* Phase, wenn die Test-Infra steht.
*/
type Row = {
id: string;
userId: string;
name: string;
description: string | null;
color: string | null;
visibility: 'private' | 'space' | 'public';
fsrsSettings: unknown;
contentHash: string | null;
createdAt: Date;
updatedAt: Date;
};
function makeFakeDb() {
const store = new Map<string, Row>();
const fakeDb = {
insert: (_table: unknown) => ({
values: (vals: Partial<Row> & { id: string; userId: string }) => ({
returning: async () => {
const row: Row = {
id: vals.id,
userId: vals.userId,
name: vals.name ?? '',
description: vals.description ?? null,
color: vals.color ?? null,
visibility: vals.visibility ?? 'private',
fsrsSettings: vals.fsrsSettings ?? {},
contentHash: vals.contentHash ?? null,
createdAt: vals.createdAt ?? new Date(),
updatedAt: vals.updatedAt ?? new Date(),
};
store.set(row.id, row);
return [row];
},
}),
}),
select: () => ({
from: (_table: unknown) => ({
where: (filter: { userId?: string; id?: string }) => {
const items = Array.from(store.values()).filter((r) => {
if (filter.userId && r.userId !== filter.userId) return false;
if (filter.id && r.id !== filter.id) return false;
return true;
});
return Object.assign(items as Row[] | Promise<Row[]>, {
limit: (_n: number) => items.slice(0, _n),
});
},
}),
}),
update: (_table: unknown) => ({
set: (patch: Partial<Row>) => ({
where: (filter: { userId: string; id: string }) => ({
returning: async () => {
const existing = store.get(filter.id);
if (!existing || existing.userId !== filter.userId) return [];
const updated = { ...existing, ...patch, updatedAt: new Date() };
store.set(updated.id, updated);
return [updated];
},
}),
}),
}),
delete: (_table: unknown) => ({
where: (filter: { userId: string; id: string }) => ({
returning: async () => {
const existing = store.get(filter.id);
if (!existing || existing.userId !== filter.userId) return [];
store.delete(filter.id);
return [{ id: filter.id }];
},
}),
}),
};
// Drizzle's eq/and dont actually pass a function-based filter; the fake-db
// shim above doesn't match real Drizzle wire-shape. So we override the
// interpretation: the test patches eq/and via a simpler comparator.
// For now this fake-DB is sufficient ONLY if the routes' .where()-args
// arrive as plain { userId, id } objects. They don't — they arrive as
// Drizzle-SQL builders. So tests below are scoped to validation/auth paths,
// not full CRUD.
return { fakeDb, store };
}
function buildApp() {
const { fakeDb } = makeFakeDb();
// Cast — the fakeDb is intentionally minimal and not a full CardsDb.
const app = new Hono();
app.route('/api/v1/decks', decksRouter({ db: fakeDb as unknown as CardsDb }));
return { app };
}
describe('decksRouter — auth-gate', () => {
it('rejects requests without X-User-Id with 401', async () => {
const { app } = buildApp();
const res = await app.request('/api/v1/decks');
expect(res.status).toBe(401);
});
it('lets through with X-User-Id (no DB call)', async () => {
const { app } = buildApp();
// POST with invalid input should reach the validation step, not 401.
const res = await app.request('/api/v1/decks', {
method: 'POST',
headers: {
'X-User-Id': 'u-1',
'Content-Type': 'application/json',
},
body: '{}',
});
expect(res.status).toBe(422);
});
});
describe('decksRouter — input validation', () => {
it('POST with empty body is 422', async () => {
const { app } = buildApp();
const res = await app.request('/api/v1/decks', {
method: 'POST',
headers: { 'X-User-Id': 'u-1', 'Content-Type': 'application/json' },
body: '{}',
});
expect(res.status).toBe(422);
const body = (await res.json()) as { error: string };
expect(body.error).toBe('invalid_input');
});
it('POST with bad color is 422', async () => {
const { app } = buildApp();
const res = await app.request('/api/v1/decks', {
method: 'POST',
headers: { 'X-User-Id': 'u-1', 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'D', color: 'red' }),
});
expect(res.status).toBe(422);
});
it('PATCH with extra prop is 422', async () => {
const { app } = buildApp();
const res = await app.request('/api/v1/decks/d-1', {
method: 'PATCH',
headers: { 'X-User-Id': 'u-1', 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'X', leak: 'bad' }),
});
expect(res.status).toBe(422);
});
});

View file

@ -0,0 +1,89 @@
import { describe, it, expect } from 'vitest';
import { Hono } from 'hono';
import { reviewsRouter } from '../src/routes/reviews.ts';
import type { CardsDb } from '../src/db/connection.ts';
function buildApp() {
const stub = {
select: () => ({
from: () => ({
innerJoin: () => ({
innerJoin: () => ({
where: () => ({ limit: () => [] }),
}),
where: () => ({
orderBy: () => ({ limit: () => [] }),
}),
}),
where: () => ({
orderBy: () => ({ limit: () => [] }),
}),
}),
}),
};
const app = new Hono();
app.route('/api/v1/reviews', reviewsRouter({ db: stub as unknown as CardsDb }));
return { app };
}
describe('reviewsRouter — auth-gate', () => {
it('GET /due ohne X-User-Id ist 401', async () => {
const { app } = buildApp();
const res = await app.request('/api/v1/reviews/due');
expect(res.status).toBe(401);
});
it('POST /grade ohne X-User-Id ist 401', async () => {
const { app } = buildApp();
const res = await app.request('/api/v1/reviews/c-1/0/grade', {
method: 'POST',
body: JSON.stringify({ rating: 'good' }),
});
expect(res.status).toBe(401);
});
});
describe('reviewsRouter — Input-Validation', () => {
it('POST mit invalid sub_index ist 422', async () => {
const { app } = buildApp();
const res = await app.request('/api/v1/reviews/c-1/-1/grade', {
method: 'POST',
headers: { 'X-User-Id': 'u-1', 'Content-Type': 'application/json' },
body: JSON.stringify({ rating: 'good' }),
});
expect(res.status).toBe(422);
});
it('POST ohne rating ist 422', async () => {
const { app } = buildApp();
const res = await app.request('/api/v1/reviews/c-1/0/grade', {
method: 'POST',
headers: { 'X-User-Id': 'u-1', 'Content-Type': 'application/json' },
body: '{}',
});
expect(res.status).toBe(422);
});
it('POST mit unknown rating ist 422', async () => {
const { app } = buildApp();
const res = await app.request('/api/v1/reviews/c-1/0/grade', {
method: 'POST',
headers: { 'X-User-Id': 'u-1', 'Content-Type': 'application/json' },
body: JSON.stringify({ rating: 'maybe' }),
});
expect(res.status).toBe(422);
});
it('POST mit gültigem rating erreicht Lookup (404 bei stub)', async () => {
const { app } = buildApp();
const res = await app.request('/api/v1/reviews/c-1/0/grade', {
method: 'POST',
headers: { 'X-User-Id': 'u-1', 'Content-Type': 'application/json' },
body: JSON.stringify({ rating: 'good' }),
});
expect(res.status).toBe(404);
const body = (await res.json()) as { error: string };
expect(body.error).toBe('not_found');
});
});