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,4 +1,4 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { describe, it, expect, vi, beforeEach, afterEach, type MockInstance } from 'vitest';
import { listMangas, createManga, getManga } from './mangas';
function ok(body: unknown): Response {
@@ -8,12 +8,19 @@ function ok(body: unknown): Response {
});
}
function fail(status: number, body = ''): Response {
return new Response(body, { status });
function envelope(status: number, code: string, message: string): Response {
return new Response(JSON.stringify({ error: { code, message } }), {
status,
headers: { 'content-type': 'application/json' }
});
}
function emptyPage() {
return { items: [], page: { limit: 50, offset: 0, total: null } };
}
describe('mangas api client', () => {
let fetchSpy: ReturnType<typeof vi.spyOn>;
let fetchSpy: MockInstance<typeof globalThis.fetch>;
beforeEach(() => {
fetchSpy = vi.spyOn(globalThis, 'fetch');
@@ -22,24 +29,48 @@ describe('mangas api client', () => {
vi.restoreAllMocks();
});
it('listMangas hits /mangas with no params by default', async () => {
fetchSpy.mockResolvedValueOnce(ok([]));
it('listMangas hits /v1/mangas with no params by default', async () => {
fetchSpy.mockResolvedValueOnce(ok(emptyPage()));
await listMangas();
expect(fetchSpy).toHaveBeenCalledTimes(1);
const url = fetchSpy.mock.calls[0][0] as string;
expect(url).toMatch(/\/mangas$/);
expect(url).toMatch(/\/v1\/mangas$/);
});
it('listMangas returns the paged envelope', async () => {
fetchSpy.mockResolvedValueOnce(
ok({
items: [
{
id: 'b1',
title: 'Berserk',
author: 'Miura',
description: null,
cover_image_path: null,
created_at: '2026-01-01T00:00:00Z',
updated_at: '2026-01-01T00:00:00Z'
}
],
page: { limit: 50, offset: 0, total: null }
})
);
const result = await listMangas();
expect(result.items).toHaveLength(1);
expect(result.items[0].title).toBe('Berserk');
expect(result.page).toEqual({ limit: 50, offset: 0, total: null });
});
it('listMangas encodes search, limit, offset', async () => {
fetchSpy.mockResolvedValueOnce(ok([]));
fetchSpy.mockResolvedValueOnce(ok(emptyPage()));
await listMangas({ search: 'one piece', limit: 10, offset: 20 });
const url = fetchSpy.mock.calls[0][0] as string;
expect(url).toMatch(/\/v1\/mangas\?/);
expect(url).toContain('search=one+piece');
expect(url).toContain('limit=10');
expect(url).toContain('offset=20');
});
it('createManga POSTs JSON', async () => {
it('createManga POSTs JSON to /v1/mangas', async () => {
fetchSpy.mockResolvedValueOnce(
ok({
id: 'abc',
@@ -53,17 +84,21 @@ describe('mangas api client', () => {
);
const m = await createManga({ title: 'Berserk', author: 'Miura' });
expect(m.title).toBe('Berserk');
const url = fetchSpy.mock.calls[0][0] as string;
expect(url).toMatch(/\/v1\/mangas$/);
const init = fetchSpy.mock.calls[0][1] as RequestInit;
expect(init.method).toBe('POST');
expect(init.headers).toMatchObject({ 'content-type': 'application/json' });
expect(JSON.parse(init.body as string)).toEqual({ title: 'Berserk', author: 'Miura' });
});
it('getManga throws ApiError on non-2xx', async () => {
fetchSpy.mockResolvedValue(fail(404, 'not found'));
it('getManga throws ApiError carrying the envelope code on non-2xx', async () => {
fetchSpy.mockResolvedValue(envelope(404, 'not_found', 'manga not found'));
await expect(getManga('missing')).rejects.toMatchObject({
name: 'ApiError',
status: 404
status: 404,
code: 'not_found',
message: 'manga not found'
});
});
});