Skip to main content

tail_fin_common/
types.rs

1use serde::{Deserialize, Serialize};
2
3#[derive(Debug, Clone, Serialize, Deserialize)]
4pub struct ActionResult {
5    pub status: String,
6    pub message: String,
7}
8
9/// Parse a browser eval result into an ActionResult.
10/// Handles JSON string responses from browser JavaScript.
11pub fn parse_action_result(value: serde_json::Value) -> Result<ActionResult, super::TailFinError> {
12    let s = value
13        .as_str()
14        .unwrap_or(r#"{"status":"failed","message":"no response"}"#);
15    Ok(serde_json::from_str(s).unwrap_or(ActionResult {
16        status: "failed".into(),
17        message: s.to_string(),
18    }))
19}
20
21#[cfg(test)]
22mod tests {
23    use super::*;
24
25    #[test]
26    fn serialize_produces_expected_json() {
27        let result = ActionResult {
28            status: "ok".into(),
29            message: "done".into(),
30        };
31        let json = serde_json::to_value(&result).unwrap();
32        assert_eq!(json["status"], "ok");
33        assert_eq!(json["message"], "done");
34        // Ensure no extra fields
35        let obj = json.as_object().unwrap();
36        assert_eq!(obj.len(), 2);
37    }
38
39    #[test]
40    fn deserialize_from_json_string() {
41        let json = r#"{"status":"error","message":"not found"}"#;
42        let result: ActionResult = serde_json::from_str(json).unwrap();
43        assert_eq!(result.status, "error");
44        assert_eq!(result.message, "not found");
45    }
46
47    #[test]
48    fn roundtrip_serialize_deserialize() {
49        let original = ActionResult {
50            status: "success".into(),
51            message: "created 3 items".into(),
52        };
53        let serialized = serde_json::to_string(&original).unwrap();
54        let deserialized: ActionResult = serde_json::from_str(&serialized).unwrap();
55        assert_eq!(deserialized.status, original.status);
56        assert_eq!(deserialized.message, original.message);
57    }
58
59    #[test]
60    fn json_format_matches_expected_shape() {
61        let result = ActionResult {
62            status: "ok".into(),
63            message: "hi".into(),
64        };
65        let json_str = serde_json::to_string(&result).unwrap();
66        assert_eq!(json_str, r#"{"status":"ok","message":"hi"}"#);
67    }
68}