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:
61
frontend/src/lib/api/client.test.ts
Normal file
61
frontend/src/lib/api/client.test.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach, type MockInstance } from 'vitest';
|
||||
import { ApiError } from './client';
|
||||
import { getManga } from './mangas';
|
||||
|
||||
describe('request error envelope parsing', () => {
|
||||
let fetchSpy: MockInstance<typeof globalThis.fetch>;
|
||||
|
||||
beforeEach(() => {
|
||||
fetchSpy = vi.spyOn(globalThis, 'fetch');
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('parses {error:{code,message}} into ApiError.code and message', async () => {
|
||||
fetchSpy.mockResolvedValueOnce(
|
||||
new Response(
|
||||
JSON.stringify({ error: { code: 'invalid_input', message: 'title is required' } }),
|
||||
{ status: 400, headers: { 'content-type': 'application/json' } }
|
||||
)
|
||||
);
|
||||
await expect(getManga('x')).rejects.toMatchObject({
|
||||
status: 400,
|
||||
code: 'invalid_input',
|
||||
message: 'title is required'
|
||||
});
|
||||
});
|
||||
|
||||
it('falls back to http_error code when body is HTML (e.g. upstream proxy)', async () => {
|
||||
fetchSpy.mockResolvedValueOnce(
|
||||
new Response('<html>upstream proxy bad</html>', {
|
||||
status: 502,
|
||||
headers: { 'content-type': 'text/html' }
|
||||
})
|
||||
);
|
||||
const err = (await getManga('x').catch((e) => e)) as ApiError;
|
||||
expect(err).toBeInstanceOf(ApiError);
|
||||
expect(err.status).toBe(502);
|
||||
expect(err.code).toBe('http_error');
|
||||
expect(err.message).toContain('upstream proxy bad');
|
||||
});
|
||||
|
||||
it('falls back to http_error code when body is empty', async () => {
|
||||
fetchSpy.mockResolvedValueOnce(new Response('', { status: 500 }));
|
||||
const err = (await getManga('x').catch((e) => e)) as ApiError;
|
||||
expect(err).toBeInstanceOf(ApiError);
|
||||
expect(err.status).toBe(500);
|
||||
expect(err.code).toBe('http_error');
|
||||
});
|
||||
|
||||
it('falls back to http_error code when JSON has no error envelope', async () => {
|
||||
fetchSpy.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ message: 'oops' }), {
|
||||
status: 500,
|
||||
headers: { 'content-type': 'application/json' }
|
||||
})
|
||||
);
|
||||
const err = (await getManga('x').catch((e) => e)) as ApiError;
|
||||
expect(err.code).toBe('http_error');
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
};
|
||||
|
||||
@@ -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'
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { request, type Manga } from './client';
|
||||
import { request, type Manga, type Page } from './client';
|
||||
|
||||
export type ListOptions = {
|
||||
search?: string;
|
||||
@@ -6,17 +6,22 @@ export type ListOptions = {
|
||||
offset?: number;
|
||||
};
|
||||
|
||||
export async function listMangas(opts: ListOptions = {}): Promise<Manga[]> {
|
||||
export type MangasPage = {
|
||||
items: Manga[];
|
||||
page: Page;
|
||||
};
|
||||
|
||||
export async function listMangas(opts: ListOptions = {}): Promise<MangasPage> {
|
||||
const params = new URLSearchParams();
|
||||
if (opts.search) params.set('search', opts.search);
|
||||
if (opts.limit != null) params.set('limit', String(opts.limit));
|
||||
if (opts.offset != null) params.set('offset', String(opts.offset));
|
||||
const qs = params.toString();
|
||||
return request<Manga[]>(`/mangas${qs ? `?${qs}` : ''}`);
|
||||
return request<MangasPage>(`/v1/mangas${qs ? `?${qs}` : ''}`);
|
||||
}
|
||||
|
||||
export async function getManga(id: string): Promise<Manga> {
|
||||
return request<Manga>(`/mangas/${encodeURIComponent(id)}`);
|
||||
return request<Manga>(`/v1/mangas/${encodeURIComponent(id)}`);
|
||||
}
|
||||
|
||||
export type NewManga = {
|
||||
@@ -26,11 +31,11 @@ export type NewManga = {
|
||||
};
|
||||
|
||||
export async function createManga(input: NewManga): Promise<Manga> {
|
||||
return request<Manga>('/mangas', {
|
||||
return request<Manga>('/v1/mangas', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(input)
|
||||
});
|
||||
}
|
||||
|
||||
export type { Manga };
|
||||
export type { Manga, Page };
|
||||
|
||||
Reference in New Issue
Block a user