feat: nest API under /api/v1, structured error envelope, paged lists

Move every handler from /api/* to /api/v1/*. /api/* is now reserved for
future versioning.

Standardise the error response shape across the API as
{"error": {"code": "snake_case", "message": "..."}}. AppError gains a
`code()` whose top-level variants are matched exhaustively without a
wildcard — new variants are a compile error until coded. 500-class
responses always emit the fixed "internal error" string and log the
real cause via tracing only.

Lock in the list pagination envelope as {"items": [...], "page": {
"limit", "offset", "total"}} and apply it to GET /api/v1/mangas. `total`
serialises as null until feat/list-search-polish lands an indexed count.

The frontend client parses the envelope into ApiError.code with an
http_error fallback for non-JSON bodies. listMangas now returns the
paged shape; the root route consumes .items. New client.test.ts covers
envelope parsing and the fallback paths.

Lockstep version bump to 0.2.0.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
MechaCat02
2026-05-16 21:41:20 +02:00
parent 6c1d04aaf4
commit ce9a01793f
18 changed files with 6121 additions and 67 deletions

View File

@@ -1,11 +1,12 @@
// All backend calls go through this module. Components and routes import
// the typed helpers below — they do not call fetch directly.
const BASE = (typeof import.meta !== 'undefined' && import.meta.env?.VITE_API_BASE) || '/api';
const BASE = import.meta.env?.VITE_API_BASE ?? '/api';
export class ApiError extends Error {
constructor(
public readonly status: number,
public readonly code: string,
message: string
) {
super(message);
@@ -13,11 +14,33 @@ export class ApiError extends Error {
}
}
type ErrorEnvelope = { error?: { code?: unknown; message?: unknown } };
export async function request<T>(path: string, init?: RequestInit): Promise<T> {
const res = await fetch(`${BASE}${path}`, init);
if (!res.ok) {
const text = await res.text().catch(() => '');
throw new ApiError(res.status, text || `${res.status} ${res.statusText}`);
let code = 'http_error';
let message = `${res.status} ${res.statusText}`;
const ct = res.headers.get('content-type') ?? '';
try {
if (ct.includes('application/json')) {
const body = (await res.json()) as ErrorEnvelope;
if (body?.error) {
if (typeof body.error.code === 'string' && body.error.code) {
code = body.error.code;
}
if (typeof body.error.message === 'string' && body.error.message) {
message = body.error.message;
}
}
} else {
const text = await res.text();
if (text) message = text;
}
} catch {
// Body wasn't parseable; keep the http_error fallback.
}
throw new ApiError(res.status, code, message);
}
return (await res.json()) as T;
}
@@ -31,3 +54,9 @@ export type Manga = {
created_at: string;
updated_at: string;
};
export type Page = {
limit: number;
offset: number;
total: number | null;
};