diff options
| author | Alexander_Kabui <alexanderkabua@gmail.com> | 2026-10-03 20:25:37 +0300 |
|---|---|---|
| committer | Alexander_Kabui <alexanderkabua@gmail.com> | 2026-10-03 20:25:37 +0300 |
| commit | fd0d45b98ec1136aeb84fc28fa647df9023abf75 (patch) | |
| tree | 05748707d319deb9668a194a90c3724a69c4f328 /src | |
| parent | 5ecc6b70e8a6ce2ba91f7808295a7d7672481d58 (diff) | |
| download | genenetwork4-fd0d45b98ec1136aeb84fc28fa647df9023abf75.tar.gz | |
Add foundation structure: config layering, response envelope, routes modules.
* src/config.rs: New module. Layered configuration, defaults -> GN4_CONF -> GN4_SECRETS -> environment, mirroring GeneNetwork3's SQL_URI convention so the two services can share configuration. Missing config files are ignored. * src/response.rs: New module. The descriptive success envelope (data + next actions) from the foundation design note (topics/gn4/gn4-api-foundation.gmi). Not yet adopted by existing endpoints; that is a deliberate wire-format change to agree on before it ships. * src/routes/mod.rs, species.rs, groups.rs: Move the species and groups handlers out of lib.rs into one module per domain, per the foundation structure. Handlers are pub; lib.rs just registers them. * src/lib.rs (app): Register the moved routes. hello_world and version predate the domain split and stay as top-level utility routes. * src/db.rs (sql_uri): Resolve through config::Config instead of reading the environment directly. * src/main.rs: Bind the port from config::Config.
Diffstat (limited to 'src')
| -rw-r--r-- | src/config.rs | 92 | ||||
| -rw-r--r-- | src/db.rs | 3 | ||||
| -rw-r--r-- | src/lib.rs | 251 | ||||
| -rw-r--r-- | src/main.rs | 4 | ||||
| -rw-r--r-- | src/response.rs | 68 | ||||
| -rw-r--r-- | src/routes/groups.rs | 152 | ||||
| -rw-r--r-- | src/routes/mod.rs | 7 | ||||
| -rw-r--r-- | src/routes/species.rs | 91 |
8 files changed, 428 insertions, 240 deletions
diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..eff8f22 --- /dev/null +++ b/src/config.rs @@ -0,0 +1,92 @@ +//! Layered configuration, mirroring GeneNetwork3's convention: +//! +//! ```text +//! built-in defaults -> GN4_CONF file -> GN4_SECRETS file -> environment +//! ``` +//! +//! GN4_CONF and GN4_SECRETS are paths to files of `KEY=VALUE` lines +//! (# comments and blank lines allowed). Splitting secrets into their +//! own file lets GN4_CONF be checked into a repo while GN4_SECRETS +//! stays out of it. Environment variables always win, so ad-hoc +//! overrides never need a file edit. + +use std::collections::HashMap; + +/// The GeneNetwork4 configuration. +pub struct Config { + /// mysql://user:password@host/database. Same SQL_URI config key + /// GeneNetwork3 uses, so the two services can share configuration. + pub sql_uri: String, + /// TCP port to bind. + pub port: u16, +} + +impl Config { + /// Load configuration from all layers, highest priority last. + pub fn load() -> Config { + let mut values = HashMap::<String, String>::new(); + + // Layer 1: built-in defaults. + values.insert("SQL_URI".to_string(), "mysql://webqtlout:webqtlout@127.0.0.1/db_webqtl".to_string()); + values.insert("GENENETWORK4_PORT".to_string(), "3000".to_string()); + + // Layers 2 and 3: config files, in increasing priority. + for env_key in ["GN4_CONF", "GN4_SECRETS"] { + if let Ok(path) = std::env::var(env_key) { + for (key, value) in load_file(&path) { + values.insert(key, value); + } + } + } + + // Layer 4: environment wins over everything. + for key in ["SQL_URI", "GENENETWORK4_PORT"] { + if let Ok(value) = std::env::var(key) { + values.insert(key.to_string(), value); + } + } + + Config { + sql_uri: values["SQL_URI"].clone(), + port: values["GENENETWORK4_PORT"] + .parse() + .expect("GENENETWORK4_PORT must be a number"), + } + } +} + +/// Parse a `KEY=VALUE` file into a map. Missing/unreadable files are +/// ignored so a stale GN4_CONF path never stops the server from +/// starting on defaults. +fn load_file(path: &str) -> HashMap<String, String> { + let Ok(contents) = std::fs::read_to_string(path) else { + return HashMap::new(); + }; + let mut map = HashMap::new(); + for line in contents.lines() { + let line = line.trim(); + if line.is_empty() || line.starts_with('#') { + continue; + } + if let Some((key, value)) = line.split_once('=') { + map.insert(key.trim().to_string(), value.trim().to_string()); + } + } + map +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn defaults_apply_with_no_files_or_env() { + // Safe only because tests run without these set; guard anyway. + if std::env::var("SQL_URI").is_ok() || std::env::var("GN4_CONF").is_ok() { + return; + } + let config = Config::load(); + assert!(config.sql_uri.contains("db_webqtl")); + assert_eq!(config.port, 3000); + } +} diff --git a/src/db.rs b/src/db.rs index 28251d7..462639e 100644 --- a/src/db.rs +++ b/src/db.rs @@ -8,8 +8,7 @@ use serde::Serialize; /// SQL_URI config key GeneNetwork3 uses, so the two services can share /// configuration. fn sql_uri() -> String { - std::env::var("SQL_URI") - .unwrap_or_else(|_| "mysql://webqtlout:webqtlout@127.0.0.1/db_webqtl".to_string()) + crate::config::Config::load().sql_uri } #[derive(Serialize, utoipa::ToSchema)] diff --git a/src/lib.rs b/src/lib.rs index 8a9142e..39ac601 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,14 +1,15 @@ -use axum::extract::{Extension, Path, Query}; -use axum::http::StatusCode; -use axum::{Json, Router}; -use serde::Serialize; +use axum::Json; +use axum::Router; use tower_http::request_id::{MakeRequestUuid, PropagateRequestIdLayer, RequestId, SetRequestIdLayer}; use utoipa::OpenApi; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; +pub mod config; mod db; mod error; +pub mod response; +mod routes; use error::ApiError; @@ -26,17 +27,17 @@ pub fn app() -> Router { let (router, api) = OpenApiRouter::with_openapi(ApiDoc::openapi()) .routes(routes!(hello_world)) .routes(routes!(version)) - .routes(routes!(species)) - .routes(routes!(species_by_name)) - .routes(routes!(groups)) - .routes(routes!(group_by_name)) - .routes(routes!(group_strains)) + .routes(routes!(routes::species::species)) + .routes(routes!(routes::species::species_by_name)) + .routes(routes!(routes::groups::groups)) + .routes(routes!(routes::groups::group_by_name)) + .routes(routes!(routes::groups::group_strains)) .split_for_parts(); router .route("/openapi.json", axum::routing::get(|| async { Json(api) })) // Assigns each request an x-request-id (if the client didn't - // already send one) and copies it onto the response, so it can - // be included in ApiError bodies (see error.rs) and correlated + // already send one) and copies it onto the response, so it can be + // included in ApiError bodies (see error.rs) and correlated // with logs. .layer(PropagateRequestIdLayer::x_request_id()) .layer(SetRequestIdLayer::x_request_id(MakeRequestUuid)) @@ -46,6 +47,8 @@ fn request_id_string(request_id: &RequestId) -> Option<String> { request_id.header_value().to_str().ok().map(str::to_string) } +// hello_world and version predate the domain-module split and don't +// belong to a data domain; kept here as top-level utility routes. #[utoipa::path(get, path = "/", responses( (status = 200, description = "Greeting", body = String), (status = 500, description = "Internal error", body = ApiError) @@ -54,7 +57,7 @@ async fn hello_world() -> &'static str { "Hello, world!" } -#[derive(Serialize, utoipa::ToSchema)] +#[derive(serde::Serialize, utoipa::ToSchema)] struct VersionInfo { name: &'static str, short_name: &'static str, @@ -78,227 +81,3 @@ async fn version() -> Json<VersionInfo> { git: env!("GN4_GIT_HASH"), }) } - -#[utoipa::path(get, path = "/species", responses( - (status = 200, description = "All species in the database", body = Vec<db::Species>), - (status = 500, description = "Database error", body = ApiError) -))] -async fn species(Extension(request_id): Extension<RequestId>) -> Result<Json<Vec<db::Species>>, ApiError> { - let rid = request_id_string(&request_id); - // mysql's Conn is blocking; run it on a blocking thread so it doesn't - // stall the async runtime. - tokio::task::spawn_blocking(db::get_all_species) - .await - .map_err(|e| { - ApiError::new( - StatusCode::INTERNAL_SERVER_ERROR, - "internal_error", - "Internal error", - e.to_string(), - "species", - ) - .with_request_id(rid.clone()) - })? - .map(Json) - .map_err(|e| { - ApiError::new( - StatusCode::INTERNAL_SERVER_ERROR, - "database_error", - "Database error", - e.to_string(), - "species", - ) - .with_request_id(rid) - }) -} - -#[utoipa::path(get, path = "/species/{species}", params( - ("species" = String, Path, description = "Species Name, FullName or SpeciesName") -), responses( - (status = 200, description = "The matching row of the Species table", body = db::SpeciesDetail), - (status = 404, description = "No matching species", body = ApiError), - (status = 500, description = "Database error", body = ApiError) -))] -async fn species_by_name( - Extension(request_id): Extension<RequestId>, - Path(species): Path<String>, -) -> Result<Json<db::SpeciesDetail>, ApiError> { - let rid = request_id_string(&request_id); - let not_found_name = species.clone(); - tokio::task::spawn_blocking(move || db::get_species_by_name(&species)) - .await - .map_err(|e| { - ApiError::new( - StatusCode::INTERNAL_SERVER_ERROR, - "internal_error", - "Internal error", - e.to_string(), - "species_by_name", - ) - .with_request_id(rid.clone()) - })? - .map_err(|e| { - ApiError::new( - StatusCode::INTERNAL_SERVER_ERROR, - "database_error", - "Database error", - e.to_string(), - "species_by_name", - ) - .with_request_id(rid.clone()) - })? - .map(Json) - .ok_or_else(|| { - ApiError::new( - StatusCode::NOT_FOUND, - "species_not_found", - "Species not found", - format!("No species matching '{not_found_name}'."), - "species_by_name", - ) - .with_request_id(rid) - .with_next("/species") - }) -} - -#[utoipa::path(get, path = "/groups", responses( - (status = 200, description = "All groups (InbredSet rows) in the database", body = Vec<db::Group>), - (status = 500, description = "Database error", body = ApiError) -))] -async fn groups(Extension(request_id): Extension<RequestId>) -> Result<Json<Vec<db::Group>>, ApiError> { - let rid = request_id_string(&request_id); - tokio::task::spawn_blocking(db::get_all_groups) - .await - .map_err(|e| { - ApiError::new( - StatusCode::INTERNAL_SERVER_ERROR, - "internal_error", - "Internal error", - e.to_string(), - "groups", - ) - .with_request_id(rid.clone()) - })? - .map(Json) - .map_err(|e| { - ApiError::new( - StatusCode::INTERNAL_SERVER_ERROR, - "database_error", - "Database error", - e.to_string(), - "groups", - ) - .with_request_id(rid) - }) -} - -#[utoipa::path(get, path = "/groups/{group}", params( - ("group" = String, Path, description = "Group InbredSetName, Name, FullName or numeric Id") -), responses( - (status = 200, description = "The matching row of the InbredSet table", body = db::GroupDetail), - (status = 404, description = "No matching group", body = ApiError), - (status = 500, description = "Database error", body = ApiError) -))] -async fn group_by_name( - Extension(request_id): Extension<RequestId>, - Path(group): Path<String>, -) -> Result<Json<db::GroupDetail>, ApiError> { - let rid = request_id_string(&request_id); - let not_found_name = group.clone(); - tokio::task::spawn_blocking(move || db::get_group_by_name(&group)) - .await - .map_err(|e| { - ApiError::new( - StatusCode::INTERNAL_SERVER_ERROR, - "internal_error", - "Internal error", - e.to_string(), - "group_by_name", - ) - .with_request_id(rid.clone()) - })? - .map_err(|e| { - ApiError::new( - StatusCode::INTERNAL_SERVER_ERROR, - "database_error", - "Database error", - e.to_string(), - "group_by_name", - ) - .with_request_id(rid.clone()) - })? - .map(Json) - .ok_or_else(|| { - ApiError::new( - StatusCode::NOT_FOUND, - "group_not_found", - "Group not found", - format!("No group matching '{not_found_name}'."), - "group_by_name", - ) - .with_request_id(rid) - .with_next("/groups") - }) -} - -#[derive(serde::Deserialize)] -struct GroupStrainsParams { - used_for_mapping: Option<bool>, -} - -#[utoipa::path(get, path = "/groups/{group}/strains", params( - ("group" = String, Path, description = "Group InbredSetName, Name, FullName or numeric Id"), - ("used_for_mapping" = Option<bool>, Query, description = "Only strains/samples used for mapping") -), responses( - (status = 200, description = "The strains/samples belonging to the group", body = Vec<db::Strain>), - (status = 404, description = "No matching group", body = ApiError), - (status = 500, description = "Database error", body = ApiError) -))] -async fn group_strains( - Extension(request_id): Extension<RequestId>, - Path(group): Path<String>, - Query(params): Query<GroupStrainsParams>, -) -> Result<Json<Vec<db::Strain>>, ApiError> { - let rid = request_id_string(&request_id); - let not_found_name = group.clone(); - let used_for_mapping = params.used_for_mapping; - tokio::task::spawn_blocking(move || { - db::get_group_by_name(&group).and_then(|group| match group { - Some(group) => db::get_group_strains(group.id, used_for_mapping).map(Some), - None => Ok(None), - }) - }) - .await - .map_err(|e| { - ApiError::new( - StatusCode::INTERNAL_SERVER_ERROR, - "internal_error", - "Internal error", - e.to_string(), - "group_strains", - ) - .with_request_id(rid.clone()) - })? - .map_err(|e| { - ApiError::new( - StatusCode::INTERNAL_SERVER_ERROR, - "database_error", - "Database error", - e.to_string(), - "group_strains", - ) - .with_request_id(rid.clone()) - })? - .map(Json) - .ok_or_else(|| { - ApiError::new( - StatusCode::NOT_FOUND, - "group_not_found", - "Group not found", - format!("No group matching '{not_found_name}'."), - "group_strains", - ) - .with_request_id(rid) - .with_next("/groups") - }) -} diff --git a/src/main.rs b/src/main.rs index 1b17f8e..58a96e2 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,7 +1,7 @@ #[tokio::main] async fn main() { - let port = std::env::var("GENENETWORK4_PORT").unwrap_or_else(|_| "3000".to_string()); - let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{port}")) + let config = genenetwork4::config::Config::load(); + let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{}", config.port)) .await .unwrap(); axum::serve(listener, genenetwork4::app()).await.unwrap(); diff --git a/src/response.rs b/src/response.rs new file mode 100644 index 0000000..55dea57 --- /dev/null +++ b/src/response.rs @@ -0,0 +1,68 @@ +//! The one descriptive success envelope, per the foundation design +//! note (topics/gn4/gn4-api-foundation.gmi): every success response +//! carries its data plus the next actions a caller (human or LLM) can +//! take. Errors carry suggestions via the shared ApiError shape in +//! error.rs. Never ad-hoc JSON per endpoint. +//! +//! Existing endpoints still return their bare payloads; migrating them +//! onto Envelope is a deliberate wire-format change to agree on the +//! thread before it ships. + +use serde::Serialize; + +/// A success response: the payload plus suggested follow-up calls. +#[derive(Serialize)] +pub struct Envelope<T: Serialize> { + pub data: T, + pub next: Vec<NextAction>, +} + +/// One suggested follow-up call. +#[derive(Serialize)] +pub struct NextAction { + /// Endpoint to call, e.g. "/species/mouse". + pub href: String, + /// What this call gives you, e.g. "Drill down into one species". + pub description: String, +} + +impl<T: Serialize> Envelope<T> { + pub fn of(data: T) -> Self { + Envelope { data, next: Vec::new() } + } + + pub fn with_next(mut self, href: &str, description: &str) -> Self { + self.next.push(NextAction { + href: href.to_string(), + description: description.to_string(), + }); + self + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn envelope_serializes_data_and_next_actions() { + let envelope = Envelope::of(vec!["mouse", "rat"]) + .with_next("/species/mouse", "Drill down into one species"); + let json = serde_json::to_value(&envelope).unwrap(); + assert_eq!( + json["data"], + serde_json::json!(["mouse", "rat"]) + ); + assert_eq!(json["next"][0]["href"], "/species/mouse"); + assert_eq!( + json["next"][0]["description"], + "Drill down into one species" + ); + } + + #[test] + fn envelope_can_carry_no_actions() { + let json = serde_json::to_value(Envelope::of(42)).unwrap(); + assert_eq!(json["next"], serde_json::json!([])); + } +} diff --git a/src/routes/groups.rs b/src/routes/groups.rs new file mode 100644 index 0000000..ad1c089 --- /dev/null +++ b/src/routes/groups.rs @@ -0,0 +1,152 @@ +//! Groups (InbredSet) domain endpoints: read-only access to the +//! InbredSet table and its strains. + +use axum::extract::{Extension, Path, Query}; +use axum::http::StatusCode; +use axum::Json; + +use crate::db; +use crate::error::ApiError; +use crate::request_id_string; + +#[utoipa::path(get, path = "/groups", responses( + (status = 200, description = "All groups (InbredSet rows) in the database", body = Vec<db::Group>), + (status = 500, description = "Database error", body = ApiError) +))] +pub async fn groups(Extension(request_id): Extension<axum::http::RequestId>) -> Result<Json<Vec<db::Group>>, ApiError> { + let rid = request_id_string(&request_id); + tokio::task::spawn_blocking(db::get_all_groups) + .await + .map_err(|e| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Internal error", + e.to_string(), + "groups", + ) + .with_request_id(rid.clone()) + })? + .map(Json) + .map_err(|e| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "database_error", + "Database error", + e.to_string(), + "groups", + ) + .with_request_id(rid) + }) +} + +#[utoipa::path(get, path = "/groups/{group}", params( + ("group" = String, Path, description = "Group InbredSetName, Name, FullName or numeric Id") +), responses( + (status = 200, description = "The matching row of the InbredSet table", body = db::GroupDetail), + (status = 404, description = "No matching group", body = ApiError), + (status = 500, description = "Database error", body = ApiError) +))] +pub async fn group_by_name( + Extension(request_id): Extension<axum::http::RequestId>, + Path(group): Path<String>, +) -> Result<Json<db::GroupDetail>, ApiError> { + let rid = request_id_string(&request_id); + let not_found_name = group.clone(); + tokio::task::spawn_blocking(move || db::get_group_by_name(&group)) + .await + .map_err(|e| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Internal error", + e.to_string(), + "group_by_name", + ) + .with_request_id(rid.clone()) + })? + .map_err(|e| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "database_error", + "Database error", + e.to_string(), + "group_by_name", + ) + .with_request_id(rid.clone()) + })? + .map(Json) + .ok_or_else(|| { + ApiError::new( + StatusCode::NOT_FOUND, + "group_not_found", + "Group not found", + format!("No group matching '{not_found_name}'."), + "group_by_name", + ) + .with_request_id(rid) + .with_next("/groups") + }) +} + +#[derive(serde::Deserialize)] +pub struct GroupStrainsParams { + used_for_mapping: Option<bool>, +} + +#[utoipa::path(get, path = "/groups/{group}/strains", params( + ("group" = String, Path, description = "Group InbredSetName, Name, FullName or numeric Id"), + ("used_for_mapping" = Option<bool>, Query, description = "Only strains/samples used for mapping") +), responses( + (status = 200, description = "The strains/samples belonging to the group", body = Vec<db::Strain>), + (status = 404, description = "No matching group", body = ApiError), + (status = 500, description = "Database error", body = ApiError) +))] +pub async fn group_strains( + Extension(request_id): Extension<axum::http::RequestId>, + Path(group): Path<String>, + Query(params): Query<GroupStrainsParams>, +) -> Result<Json<Vec<db::Strain>>, ApiError> { + let rid = request_id_string(&request_id); + let not_found_name = group.clone(); + let used_for_mapping = params.used_for_mapping; + tokio::task::spawn_blocking(move || { + db::get_group_by_name(&group).and_then(|group| match group { + Some(group) => db::get_group_strains(group.id, used_for_mapping).map(Some), + None => Ok(None), + }) + }) + .await + .map_err(|e| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Internal error", + e.to_string(), + "group_strains", + ) + .with_request_id(rid.clone()) + })? + .map_err(|e| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "database_error", + "Database error", + e.to_string(), + "group_strains", + ) + .with_request_id(rid.clone()) + })? + .map(Json) + .ok_or_else(|| { + ApiError::new( + StatusCode::NOT_FOUND, + "group_not_found", + "Group not found", + format!("No group matching '{not_found_name}'."), + "group_strains", + ) + .with_request_id(rid) + .with_next("/groups") + }) +} diff --git a/src/routes/mod.rs b/src/routes/mod.rs new file mode 100644 index 0000000..71d51e0 --- /dev/null +++ b/src/routes/mod.rs @@ -0,0 +1,7 @@ +//! One module per GeneNetwork API domain, per the foundation design +//! note. Each module owns its handlers, path/query parameter structs +//! and utoipa annotations for one domain; lib.rs just registers them +//! on the router. + +pub mod groups; +pub mod species; diff --git a/src/routes/species.rs b/src/routes/species.rs new file mode 100644 index 0000000..29957ec --- /dev/null +++ b/src/routes/species.rs @@ -0,0 +1,91 @@ +//! Species domain endpoints: read-only access to the Species table. + +use axum::extract::{Extension, Path}; +use axum::http::StatusCode; +use axum::Json; + +use crate::db; +use crate::error::ApiError; +use crate::request_id_string; + +#[utoipa::path(get, path = "/species", responses( + (status = 200, description = "All species in the database", body = Vec<db::Species>), + (status = 500, description = "Database error", body = ApiError) +))] +pub async fn species(Extension(request_id): Extension<axum::http::RequestId>) -> Result<Json<Vec<db::Species>>, ApiError> { + let rid = request_id_string(&request_id); + // mysql's Conn is blocking; run it on a blocking thread so it doesn't + // stall the async runtime. + tokio::task::spawn_blocking(db::get_all_species) + .await + .map_err(|e| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Internal error", + e.to_string(), + "species", + ) + .with_request_id(rid.clone()) + })? + .map(Json) + .map_err(|e| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "database_error", + "Database error", + e.to_string(), + "species", + ) + .with_request_id(rid) + }) +} + +#[utoipa::path(get, path = "/species/{species}", params( + ("species" = String, Path, description = "Species Name, FullName or SpeciesName") +), responses( + (status = 200, description = "The matching row of the Species table", body = db::SpeciesDetail), + (status = 404, description = "No matching species", body = ApiError), + (status = 500, description = "Database error", body = ApiError) +))] +pub async fn species_by_name( + Extension(request_id): Extension<axum::http::RequestId>, + Path(species): Path<String>, +) -> Result<Json<db::SpeciesDetail>, ApiError> { + let rid = request_id_string(&request_id); + let not_found_name = species.clone(); + tokio::task::spawn_blocking(move || db::get_species_by_name(&species)) + .await + .map_err(|e| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Internal error", + e.to_string(), + "species_by_name", + ) + .with_request_id(rid.clone()) + })? + .map_err(|e| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "database_error", + "Database error", + e.to_string(), + "species_by_name", + ) + .with_request_id(rid.clone()) + })? + .map(Json) + .ok_or_else(|| { + ApiError::new( + StatusCode::NOT_FOUND, + "species_not_found", + "Species not found", + format!("No species matching '{not_found_name}'."), + "species_by_name", + ) + .with_request_id(rid) + .with_next("/species") + }) +} |
