about summary refs log tree commit diff
path: root/src/response.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/response.rs')
-rw-r--r--src/response.rs68
1 files changed, 68 insertions, 0 deletions
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!([]));
+    }
+}