cards/docs/marketplace/archive/code/services/authors.ts
Till JS 7dbbf63523 Phase 12 R2: Marketplace-Backend α + β — Authors + Deck-Init + Publish
Routes (additiv unter /api/v1/marketplace/*):
- POST/GET /authors/me — eigenes Author-Profil anlegen/updaten/lesen
- GET /authors/:slug — public Profile-Lookup (banned-reason gestrippt)
- POST /decks — Deck-Init (Slug-Validation + Pflicht-Author-Profil +
  CHECK auf paid + Pro-License)
- POST /decks/:slug/publish — Versions-Snapshot mit per-Karte
  cardContentHash aus @cards/domain, per-Version-Hash, AI-Mod-Stub-Log,
  atomarer latest_version_id-Bump in Drizzle-Transaction
- PATCH /decks/:slug — Metadaten-Update (Owner-Only)
- GET /decks/:slug — Public-Detail mit optional-auth-Middleware

Geport aus cards-decommission-base:services/cards-server/, mit
Greenfield-Anpassungen:
- Hashing über @cards/domain.cardContentHash (gemeinsame SoT
  zwischen privatem cards.cards und marketplace.deck_cards), per-
  Version-Hash als SHA-256 über sortierte Karten-Hashes mit Ord-Prefix
- AI-Moderation als R2-Stub (pass+rationale+model='stub'),
  echte mana-llm-Anbindung in späterer Welle
- Auth-Middleware-Shape an Greenfield (userId/tier/authMode in
  c.get(...) statt user-Object), optional-auth als Schwester für
  anonymen Public-Read
- Hono-typing: outer Marketplace-Decks-Router ist Partial<AuthVars>
  weil Public-GET kein JWT braucht; Auth-Subroute ist strict

Lese-Referenz:
- 3331 LOC altes cards-server-Code (routes, services, middleware,
  lib) unter docs/marketplace/archive/code/ archiviert. Read-only,
  nicht im Build-Path.

Verifikation:
- 16 neue Vitest-Tests (Slug + Version-Hash), 72 gesamt grün
- type-check 0 errors
- E2E-Smoke gegen lokale cards-api: Cardecky-Author + Deck
  r2-stoische-ethik mit 3 Karten v1.0.0 (basic + basic + cloze),
  per-Karten-Hashes geschrieben, ai_moderation_log-Row da, semver-409
  + paid-422-Errors verifiziert. Smoke-Daten danach aufgeräumt.

Verbleibend für R3+: Discovery (explore + search), Engagement (stars/
subscribe/fork), Smart-Merge mit FSRS-State-Erhalt; danach R4 PRs +
Card-Discussions, R5 Frontend-Routes.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 15:13:58 +02:00

104 lines
2.9 KiB
TypeScript

/**
* Author service — CRUD on `cards.authors` plus the lookups the
* routes need (by-slug, by-userId).
*
* Slug is unique per author. We don't auto-suggest slugs server-side;
* the client picks one and we validate. If a user changes their slug,
* the old slug isn't preserved (no redirects yet — Phase η maybe).
*/
import { eq } from 'drizzle-orm';
import type { Database } from '../db/connection';
import { authors } from '../db/schema';
import { validateSlug } from '../lib/slug';
import { BadRequestError, ConflictError, NotFoundError } from '../lib/errors';
export interface AuthorInput {
slug: string;
displayName: string;
bio?: string;
avatarUrl?: string;
pseudonym?: boolean;
}
export class AuthorService {
constructor(private readonly db: Database) {}
async upsertMe(userId: string, input: AuthorInput) {
const validation = validateSlug(input.slug);
if (!validation.ok) {
throw new BadRequestError(`Slug invalid: ${validation.reason}`);
}
// Slug must be free or already owned by us.
const existingBySlug = await this.db.query.authors.findFirst({
where: eq(authors.slug, input.slug),
});
if (existingBySlug && existingBySlug.userId !== userId) {
throw new ConflictError('Slug already taken');
}
const existing = await this.db.query.authors.findFirst({
where: eq(authors.userId, userId),
});
if (existing) {
const [updated] = await this.db
.update(authors)
.set({
slug: input.slug,
displayName: input.displayName,
bio: input.bio,
avatarUrl: input.avatarUrl,
pseudonym: input.pseudonym ?? existing.pseudonym,
})
.where(eq(authors.userId, userId))
.returning();
return updated;
}
const [created] = await this.db
.insert(authors)
.values({
userId,
slug: input.slug,
displayName: input.displayName,
bio: input.bio,
avatarUrl: input.avatarUrl,
pseudonym: input.pseudonym ?? false,
})
.returning();
return created;
}
async getByUserId(userId: string) {
const row = await this.db.query.authors.findFirst({ where: eq(authors.userId, userId) });
return row ?? null;
}
/** Public profile lookup — strips bannedReason etc. */
async getPublicBySlug(slug: string) {
const row = await this.db.query.authors.findFirst({ where: eq(authors.slug, slug) });
if (!row) throw new NotFoundError('Author not found');
return {
slug: row.slug,
displayName: row.displayName,
bio: row.bio,
avatarUrl: row.avatarUrl,
joinedAt: row.joinedAt,
pseudonym: row.pseudonym,
verifiedMana: row.verifiedMana,
verifiedCommunity: row.verifiedCommunity,
banned: row.bannedAt !== null,
};
}
async assertNotBanned(userId: string) {
const row = await this.getByUserId(userId);
if (!row) throw new BadRequestError('You need an author profile first (POST /v1/authors/me).');
if (row.bannedAt) {
throw new BadRequestError(`Author banned: ${row.bannedReason ?? 'no reason given'}`);
}
return row;
}
}