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:
2479
backend/Cargo.lock
generated
Normal file
2479
backend/Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "mangalord"
|
||||
version = "0.1.0"
|
||||
version = "0.2.0"
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
|
||||
@@ -4,6 +4,7 @@ use axum::{Json, Router};
|
||||
use serde::Deserialize;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::api::pagination::PagedResponse;
|
||||
use crate::app::AppState;
|
||||
use crate::domain::manga::{Manga, NewManga};
|
||||
use crate::error::{AppError, AppResult};
|
||||
@@ -32,13 +33,16 @@ fn default_limit() -> i64 {
|
||||
async fn list(
|
||||
State(state): State<AppState>,
|
||||
Query(params): Query<ListParams>,
|
||||
) -> AppResult<Json<Vec<Manga>>> {
|
||||
) -> AppResult<Json<PagedResponse<Manga>>> {
|
||||
let limit = params.limit.clamp(1, 200);
|
||||
let offset = params.offset.max(0);
|
||||
let q = repo::manga::ListQuery {
|
||||
search: params.search.filter(|s| !s.trim().is_empty()),
|
||||
limit: params.limit.clamp(1, 200),
|
||||
offset: params.offset.max(0),
|
||||
limit,
|
||||
offset,
|
||||
};
|
||||
Ok(Json(repo::manga::list(&state.db, &q).await?))
|
||||
let items = repo::manga::list(&state.db, &q).await?;
|
||||
Ok(Json(PagedResponse::new(items, limit, offset)))
|
||||
}
|
||||
|
||||
async fn get_one(
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
pub mod files;
|
||||
pub mod health;
|
||||
pub mod mangas;
|
||||
pub mod pagination;
|
||||
|
||||
use axum::Router;
|
||||
|
||||
|
||||
30
backend/src/api/pagination.rs
Normal file
30
backend/src/api/pagination.rs
Normal file
@@ -0,0 +1,30 @@
|
||||
//! Shared pagination envelope for list endpoints.
|
||||
//!
|
||||
//! `total` is `Option<i64>` and is always serialised — `null` when the
|
||||
//! handler hasn't computed it yet, a number once it has. The shape is fixed
|
||||
//! across `/mangas`, `/chapters`, `/bookmarks`, etc. so consumers can
|
||||
//! handle pagination uniformly.
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct PageInfo {
|
||||
pub limit: i64,
|
||||
pub offset: i64,
|
||||
pub total: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct PagedResponse<T> {
|
||||
pub items: Vec<T>,
|
||||
pub page: PageInfo,
|
||||
}
|
||||
|
||||
impl<T> PagedResponse<T> {
|
||||
pub fn new(items: Vec<T>, limit: i64, offset: i64) -> Self {
|
||||
Self {
|
||||
items,
|
||||
page: PageInfo { limit, offset, total: None },
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -30,7 +30,7 @@ pub async fn build(config: Config) -> anyhow::Result<Router> {
|
||||
/// so they can swap in a test DB pool and a `tempfile`-backed storage.
|
||||
pub fn router(state: AppState) -> Router {
|
||||
Router::new()
|
||||
.nest("/api", crate::api::routes())
|
||||
.nest("/api/v1", crate::api::routes())
|
||||
.with_state(state)
|
||||
.layer(TraceLayer::new_for_http())
|
||||
}
|
||||
|
||||
@@ -21,11 +21,30 @@ pub enum AppError {
|
||||
|
||||
pub type AppResult<T> = Result<T, AppError>;
|
||||
|
||||
impl AppError {
|
||||
/// Stable, snake_case code that clients pattern-match on. Every top-level
|
||||
/// variant is matched explicitly — adding a new variant without giving it
|
||||
/// a code is a compile error, on purpose.
|
||||
pub fn code(&self) -> &'static str {
|
||||
match self {
|
||||
AppError::NotFound => "not_found",
|
||||
AppError::InvalidInput(_) => "invalid_input",
|
||||
AppError::Database(sqlx::Error::RowNotFound) => "not_found",
|
||||
AppError::Database(_) => "internal_error",
|
||||
AppError::Storage(StorageError::NotFound) => "not_found",
|
||||
AppError::Storage(StorageError::BadKey) => "bad_file_key",
|
||||
AppError::Storage(StorageError::Io(_)) => "internal_error",
|
||||
AppError::Other(_) => "internal_error",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoResponse for AppError {
|
||||
fn into_response(self) -> Response {
|
||||
let code = self.code();
|
||||
let (status, message) = match &self {
|
||||
AppError::NotFound => (StatusCode::NOT_FOUND, self.to_string()),
|
||||
AppError::InvalidInput(_) => (StatusCode::BAD_REQUEST, self.to_string()),
|
||||
AppError::NotFound => (StatusCode::NOT_FOUND, "not found".to_string()),
|
||||
AppError::InvalidInput(msg) => (StatusCode::BAD_REQUEST, msg.clone()),
|
||||
AppError::Database(sqlx::Error::RowNotFound) => {
|
||||
(StatusCode::NOT_FOUND, "not found".to_string())
|
||||
}
|
||||
@@ -40,6 +59,22 @@ impl IntoResponse for AppError {
|
||||
(StatusCode::INTERNAL_SERVER_ERROR, "internal error".to_string())
|
||||
}
|
||||
};
|
||||
(status, Json(json!({ "error": message }))).into_response()
|
||||
let body = json!({ "error": { "code": code, "message": message } });
|
||||
(status, Json(body)).into_response()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn codes_are_stable() {
|
||||
assert_eq!(AppError::NotFound.code(), "not_found");
|
||||
assert_eq!(AppError::InvalidInput("x".into()).code(), "invalid_input");
|
||||
assert_eq!(AppError::Storage(StorageError::BadKey).code(), "bad_file_key");
|
||||
assert_eq!(AppError::Storage(StorageError::NotFound).code(), "not_found");
|
||||
assert_eq!(AppError::Database(sqlx::Error::RowNotFound).code(), "not_found");
|
||||
assert_eq!(AppError::Other(anyhow::anyhow!("oops")).code(), "internal_error");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,29 +8,39 @@ use tower::ServiceExt;
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn list_is_empty_initially(pool: PgPool) {
|
||||
let h = common::harness(pool);
|
||||
let resp = h.app.oneshot(common::get("/api/mangas")).await.unwrap();
|
||||
let resp = h.app.oneshot(common::get("/api/v1/mangas")).await.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
assert_eq!(common::body_json(resp).await, json!([]));
|
||||
let body = common::body_json(resp).await;
|
||||
assert_eq!(body["items"], json!([]));
|
||||
assert_eq!(body["page"]["limit"], 50);
|
||||
assert_eq!(body["page"]["offset"], 0);
|
||||
assert!(body["page"]["total"].is_null());
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn create_then_list_roundtrip(pool: PgPool) {
|
||||
let h = common::harness(pool);
|
||||
|
||||
let created = h.app.clone().oneshot(common::post_json(
|
||||
"/api/mangas",
|
||||
let created = h
|
||||
.app
|
||||
.clone()
|
||||
.oneshot(common::post_json(
|
||||
"/api/v1/mangas",
|
||||
json!({ "title": "Berserk", "author": "Kentaro Miura", "description": null }),
|
||||
)).await.unwrap();
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(created.status(), StatusCode::OK);
|
||||
let body = common::body_json(created).await;
|
||||
assert_eq!(body["title"], "Berserk");
|
||||
assert_eq!(body["author"], "Kentaro Miura");
|
||||
assert!(body["id"].as_str().is_some());
|
||||
|
||||
let listed = h.app.oneshot(common::get("/api/mangas")).await.unwrap();
|
||||
let listed = h.app.oneshot(common::get("/api/v1/mangas")).await.unwrap();
|
||||
let listed_body = common::body_json(listed).await;
|
||||
assert_eq!(listed_body.as_array().unwrap().len(), 1);
|
||||
assert_eq!(listed_body[0]["title"], "Berserk");
|
||||
let items = listed_body["items"].as_array().unwrap();
|
||||
assert_eq!(items.len(), 1);
|
||||
assert_eq!(items[0]["title"], "Berserk");
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
@@ -42,36 +52,78 @@ async fn search_filters_by_title_and_author(pool: PgPool) {
|
||||
("Berserk", "Kentaro Miura"),
|
||||
("Vinland Saga", "Makoto Yukimura"),
|
||||
] {
|
||||
let _ = h.app.clone().oneshot(common::post_json(
|
||||
"/api/mangas",
|
||||
let _ = h
|
||||
.app
|
||||
.clone()
|
||||
.oneshot(common::post_json(
|
||||
"/api/v1/mangas",
|
||||
json!({ "title": title, "author": author }),
|
||||
)).await.unwrap();
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
let resp = h.app.clone().oneshot(common::get("/api/mangas?search=miura")).await.unwrap();
|
||||
let resp = h
|
||||
.app
|
||||
.clone()
|
||||
.oneshot(common::get("/api/v1/mangas?search=miura"))
|
||||
.await
|
||||
.unwrap();
|
||||
let body = common::body_json(resp).await;
|
||||
let titles: Vec<&str> = body.as_array().unwrap().iter().map(|m| m["title"].as_str().unwrap()).collect();
|
||||
let titles: Vec<&str> = body["items"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|m| m["title"].as_str().unwrap())
|
||||
.collect();
|
||||
assert_eq!(titles, vec!["Berserk"]);
|
||||
|
||||
let resp = h.app.oneshot(common::get("/api/mangas?search=saga")).await.unwrap();
|
||||
let resp = h
|
||||
.app
|
||||
.oneshot(common::get("/api/v1/mangas?search=saga"))
|
||||
.await
|
||||
.unwrap();
|
||||
let body = common::body_json(resp).await;
|
||||
let titles: Vec<&str> = body.as_array().unwrap().iter().map(|m| m["title"].as_str().unwrap()).collect();
|
||||
let titles: Vec<&str> = body["items"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|m| m["title"].as_str().unwrap())
|
||||
.collect();
|
||||
assert_eq!(titles, vec!["Vinland Saga"]);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn create_rejects_empty_title(pool: PgPool) {
|
||||
async fn create_rejects_empty_title_with_envelope(pool: PgPool) {
|
||||
let h = common::harness(pool);
|
||||
let resp = h.app.oneshot(common::post_json(
|
||||
"/api/mangas",
|
||||
let resp = h
|
||||
.app
|
||||
.oneshot(common::post_json(
|
||||
"/api/v1/mangas",
|
||||
json!({ "title": " ", "author": null }),
|
||||
)).await.unwrap();
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
||||
let body = common::body_json(resp).await;
|
||||
assert_eq!(body["error"]["code"], "invalid_input");
|
||||
let msg = body["error"]["message"].as_str().expect("message is string");
|
||||
assert!(!msg.is_empty(), "message should be non-empty");
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn get_unknown_id_is_404(pool: PgPool) {
|
||||
async fn get_unknown_id_is_404_with_envelope(pool: PgPool) {
|
||||
let h = common::harness(pool);
|
||||
let resp = h.app.oneshot(common::get("/api/mangas/00000000-0000-0000-0000-000000000000")).await.unwrap();
|
||||
let resp = h
|
||||
.app
|
||||
.oneshot(common::get(
|
||||
"/api/v1/mangas/00000000-0000-0000-0000-000000000000",
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
|
||||
let body = common::body_json(resp).await;
|
||||
assert_eq!(body["error"]["code"], "not_found");
|
||||
let msg = body["error"]["message"].as_str().expect("message is string");
|
||||
assert!(!msg.is_empty(), "message should be non-empty");
|
||||
}
|
||||
|
||||
@@ -1,3 +1,8 @@
|
||||
// Shared test helpers. Each integration test binary picks the subset it needs,
|
||||
// so dead-code lints on the unused helpers fire per-binary; suppress at the
|
||||
// module level.
|
||||
#![allow(dead_code)]
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::body::Body;
|
||||
|
||||
@@ -7,7 +7,7 @@ use tower::ServiceExt;
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn health_returns_ok(pool: PgPool) {
|
||||
let h = common::harness(pool);
|
||||
let resp = h.app.oneshot(common::get("/api/health")).await.unwrap();
|
||||
let resp = h.app.oneshot(common::get("/api/v1/health")).await.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
let body = common::body_json(resp).await;
|
||||
assert_eq!(body["status"], "ok");
|
||||
|
||||
@@ -1,18 +1,20 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
// These E2E tests run against the dev server (vite on :5173) which proxies
|
||||
// /api to the backend. Set E2E_BASE_URL to point at a different deployment.
|
||||
// These E2E tests run against the SvelteKit dev server, which proxies /api
|
||||
// to the backend. Playwright starts vite via `webServer` (see
|
||||
// playwright.config.ts) unless E2E_BASE_URL points at a different deployment.
|
||||
//
|
||||
// A live backend (and Postgres) must be reachable. Routes mock the network
|
||||
// where possible to keep journeys deterministic.
|
||||
// Routes are mocked at the page level so the journeys are deterministic and
|
||||
// don't require a live backend.
|
||||
|
||||
const emptyPage = { items: [], page: { limit: 50, offset: 0, total: null } };
|
||||
|
||||
test('home page renders the Mangalord heading and search input', async ({ page }) => {
|
||||
// Mock the list endpoint so the test doesn't depend on DB state.
|
||||
await page.route('**/api/mangas*', async (route) => {
|
||||
await page.route('**/api/v1/mangas*', async (route) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify([])
|
||||
body: JSON.stringify(emptyPage)
|
||||
});
|
||||
});
|
||||
|
||||
@@ -24,10 +26,10 @@ test('home page renders the Mangalord heading and search input', async ({ page }
|
||||
|
||||
test('search updates the manga list', async ({ page }) => {
|
||||
let lastSearch: string | null = null;
|
||||
await page.route('**/api/mangas*', async (route) => {
|
||||
await page.route('**/api/v1/mangas*', async (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
lastSearch = url.searchParams.get('search');
|
||||
const body =
|
||||
const items =
|
||||
lastSearch === 'berserk'
|
||||
? [
|
||||
{
|
||||
@@ -44,7 +46,7 @@ test('search updates the manga list', async ({ page }) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(body)
|
||||
body: JSON.stringify({ items, page: { limit: 50, offset: 0, total: null } })
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
3316
frontend/package-lock.json
generated
Normal file
3316
frontend/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "mangalord-frontend",
|
||||
"version": "0.1.0",
|
||||
"version": "0.2.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
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 };
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
loading = true;
|
||||
error = null;
|
||||
try {
|
||||
mangas = await listMangas({ search: search.trim() || undefined });
|
||||
mangas = (await listMangas({ search: search.trim() || undefined })).items;
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
} finally {
|
||||
|
||||
Reference in New Issue
Block a user