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:
@@ -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");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user