about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorPjotr Prins <pjotr.public01@thebird.nl>2026-11-17 11:25:20 +0000
committerPjotr Prins <pjotr.public01@thebird.nl>2026-11-17 11:25:20 +0000
commitab710df0a1502b851292b61a1052585374c40ea3 (patch)
tree70c1b9695065f9d1438813b1f560d6bf0ed26ee3 /src
parent2df90559ca597c0d35daf68e8648f8a46c823787 (diff)
downloadgenenetwork4-ab710df0a1502b851292b61a1052585374c40ea3.tar.gz
groups: limit_to / ids_only / names_only, with the old shape as the default
The first of the six listings, and the pattern for the other five: the answer
type becomes `Rows` (untagged -- `Objects` or `Plain`), and *no listing
parameters means the old answer*, so this cannot break a client that already
exists. Untagged matters: the wire shape is a plain array either way, so a
wrapper object would have been a breaking change dressed as a feature.

Verified on the deployed build:

  GET /groups?species=mouse                    59 objects, keys as before
  GET /groups?species=mouse&names_only=true    59 strings, first "AKXD"
  GET /groups?ids_only=true&limit_to=BXD,NOPE  ["1"], note names "nope"
  GET /groups?ids_only=true&names_only=true    422 invalid_listing

The note for a limit_to value that matched nothing is the point of that
parameter's error path: "my group is missing" is what a silent empty answer
makes impossible to diagnose.

`listing.shape` keeps the full rows as objects for the default path, so no
client sees a serialisation round-trip; `Rows::Plain` takes the field that was
matched. The other five handlers get the same three edits plus their utoipa
body type, which is the mechanical part that needs care.
Diffstat (limited to 'src')
-rw-r--r--src/listing.rs47
-rw-r--r--src/routes/groups.rs49
2 files changed, 92 insertions, 4 deletions
diff --git a/src/listing.rs b/src/listing.rs
index fa42cb5..1e659ab 100644
--- a/src/listing.rs
+++ b/src/listing.rs
@@ -28,6 +28,25 @@
 
 use serde::Deserialize;
 
+/// What a listing answers with.
+///
+/// `Objects` is the shape the API has always had, and it stays the default: a
+/// caller who sends no listing parameters gets exactly what it got before, so
+/// adding this cannot break an existing client. `Plain` is the opt-in slim form
+/// (`ids_only` / `names_only`), one value per row.
+///
+/// Untagged because the wire shapes are a plain JSON array either way -- the
+/// difference is what is *in* the array, not how it is wrapped, and a wrapper
+/// would have been a breaking change dressed as a feature.
+#[derive(Debug, Clone, serde::Serialize, utoipa::ToSchema)]
+#[serde(untagged)]
+pub enum Rows {
+    /// One serialised row per entry, the shape every listing has always had.
+    Objects(Vec<serde_json::Value>),
+    /// One identifier per entry, from `ids_only` or `names_only`.
+    Plain(Vec<String>),
+}
+
 /// Query parameters three listings share.
 #[derive(Debug, Clone, Default, Deserialize)]
 pub struct ListingParams {
@@ -75,6 +94,34 @@ impl Listing {
         }
     }
 
+    /// Shape already-serialised rows into a [`Rows`] body.
+    ///
+    /// `rows` is the full form; `Listing::Full` hands it back untouched, so the
+    /// default answer is the old answer.
+    pub fn shape(
+        &self,
+        rows: Vec<serde_json::Value>,
+        limit_to: Option<&str>,
+    ) -> (Rows, Vec<String>) {
+        let as_value = serde_json::Value::Array(rows);
+        let (shaped, missing) = self.apply(&as_value, limit_to);
+        let entries = shaped.as_array().cloned().unwrap_or_default();
+        let body = match self {
+            Listing::Full => Rows::Objects(entries),
+            Listing::Only(_) => Rows::Plain(
+                entries
+                    .into_iter()
+                    .filter_map(|value| match value {
+                        serde_json::Value::String(text) => Some(text),
+                        serde_json::Value::Number(number) => Some(number.to_string()),
+                        _ => None,
+                    })
+                    .collect(),
+            ),
+        };
+        (body, missing)
+    }
+
     /// Shape `rows` (already serialised) according to the parameters.
     ///
     /// Returns the shaped array and, for a `limit_to` that matched nothing, the
diff --git a/src/routes/groups.rs b/src/routes/groups.rs
index dd59165..eca9574 100644
--- a/src/routes/groups.rs
+++ b/src/routes/groups.rs
@@ -30,6 +30,16 @@ pub struct GroupsParams {
     /// Keep groups whose name, display name or full name contains this
     /// text, case-insensitively, e.g. "alzheimer".
     pub q: Option<String>,
+    /// Keep only these ids or names, comma-separated. Values that match nothing
+    /// are named in the reply's note.
+    #[serde(default)]
+    pub limit_to: Option<String>,
+    /// Answer with one id per group instead of objects.
+    #[serde(default)]
+    pub ids_only: Option<bool>,
+    /// Answer with one name per group instead of objects.
+    #[serde(default)]
+    pub names_only: Option<bool>,
 }
 
 fn contains_ci(field: &Option<String>, needle: &str) -> bool {
@@ -39,7 +49,8 @@ fn contains_ci(field: &Option<String>, needle: &str) -> bool {
 }
 
 #[utoipa::path(get, path = "/groups", summary = "List all groups (populations; InbredSet rows), optionally filtered", params(GroupsParams), responses(
-    (status = 200, description = "The groups (InbredSet rows), with family and species name", body = Envelope<Vec<db::Group>>),
+    (status = 200, description = "The groups (InbredSet rows), with family and species name; \
+`ids_only`/`names_only` answer one value per group instead", body = Envelope<crate::listing::Rows>),
     Unauthorized,
     (status = 500, description = "Database error", body = ApiError)
 ))]
@@ -48,8 +59,24 @@ pub async fn groups(
     ctx: Ctx,
     _token: AuthToken,
     Query(params): Query<GroupsParams>,
-) -> Result<Json<Envelope<Vec<db::Group>>>, ApiError> {
+) -> Result<Json<Envelope<crate::listing::Rows>>, ApiError> {
     let rid = ctx.request_info();
+    let listing = crate::listing::Listing::parse(&crate::listing::ListingParams {
+        limit_to: params.limit_to.clone(),
+        ids_only: params.ids_only,
+        names_only: params.names_only,
+    })
+    .map_err(|detail| {
+        ApiError::new(
+            StatusCode::UNPROCESSABLE_ENTITY,
+            "invalid_listing",
+            "Invalid listing parameters",
+            detail,
+            "groups",
+        )
+        .with_request_id(rid.clone())
+    })?;
+    let listing_rid = rid.clone();
     tokio::task::spawn_blocking(db::get_all_groups)
         .await
         .map_err(|e| {
@@ -86,10 +113,24 @@ pub async fn groups(
                     })
                 })
                 .collect();
-            Json(ctx.envelope(groups).with_next(
+            let rows: Vec<serde_json::Value> = groups
+                .iter()
+                .map(|group| serde_json::to_value(group).unwrap_or(serde_json::Value::Null))
+                .collect();
+            let (shaped, missing) = listing.shape(rows, params.limit_to.as_deref());
+            let _ = &listing_rid;
+            let mut envelope = ctx.envelope(shaped).with_next(
                 "/species",
                 "The species the groups belong to (filter groups with ?species=<name>)",
-            ))
+            );
+            if !missing.is_empty() {
+                envelope = envelope.with_note(&format!(
+                    "limit_to named {} value(s) that matched no group: {}",
+                    missing.len(),
+                    missing.join(", ")
+                ));
+            }
+            Json(envelope)
         })
         .map_err(|e| ApiError::from_db(e, "groups").with_request_id(rid))
 }