bachs-sdk 0.1.0

Unofficial Rust SDK for the Bachs API — payments and billing for internet businesses.
Documentation
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// An ISO 8601 UTC timestamp string, as returned by the API (e.g.
/// `"2026-07-13T14:00:00.000Z"`). Kept as a plain `String` so this crate
/// doesn't force a `chrono`/`time` dependency on you — parse it with
/// whichever date/time crate you already use.
pub type Timestamp = String;

/// Free-form key-value data you attach to a resource. Bachs returns it
/// unchanged on every read.
pub type Metadata = HashMap<String, serde_json::Value>;

/// Envelope returned by every list endpoint: `{ items, pagination }`.
#[derive(Debug, Clone, Deserialize)]
pub struct ListResponse<T> {
    pub items: Vec<T>,
    pub pagination: Pagination,
}

/// Cursor-based pagination metadata. Field names follow the shape documented
/// under "Pagination" in the Bachs docs (`/guides/pagination`); if your
/// account's API version returns extra fields, they'll simply be ignored
/// here.
#[derive(Debug, Clone, Deserialize)]
pub struct Pagination {
    #[serde(default)]
    pub next_cursor: Option<String>,
    #[serde(default)]
    pub has_more: bool,
    #[serde(default)]
    pub total_count: Option<u64>,
}

/// Common list query parameters accepted by list endpoints.
#[derive(Debug, Clone, Default, Serialize)]
pub struct ListParams {
    #[serde(skip)]
    pub limit: Option<u32>,
    #[serde(skip)]
    pub cursor: Option<String>,
}

impl ListParams {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn limit(mut self, limit: u32) -> Self {
        self.limit = Some(limit);
        self
    }

    pub fn cursor(mut self, cursor: impl Into<String>) -> Self {
        self.cursor = Some(cursor.into());
        self
    }

    pub(crate) fn to_query(&self) -> Vec<(&str, String)> {
        let mut q = Vec::new();
        if let Some(limit) = self.limit {
            q.push(("limit", limit.to_string()));
        }
        if let Some(cursor) = &self.cursor {
            q.push(("cursor", cursor.clone()));
        }
        q
    }
}

/// A billing/postal address. `line1` and `country` are required whenever an
/// address is supplied at all.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Address {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub line1: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub line2: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub city: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub state: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub postal_code: Option<String>,
    /// Two-letter ISO 3166-1 alpha-2 country code, e.g. `"NG"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub country: Option<String>,
}

/// An amount of money. Always a decimal string at the currency's precision
/// (e.g. `"29.00"`), paired with an ISO 4217 currency code — never minor
/// units. See the Bachs docs' Agent Instructions for this convention.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Money {
    pub amount: String,
    pub currency: String,
}

/// A resource whose exact response schema isn't pinned down by the public
/// docs yet. Known/likely fields are typed; everything else the API returns
/// is preserved in `extra` rather than causing a deserialization error, so
/// this SDK degrades gracefully as the API evolves. Look up additional
/// fields with `extra.get("field_name")`.
#[derive(Debug, Clone, Deserialize)]
pub struct FlexObject {
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

impl FlexObject {
    /// The resource's `..._id` field, if present under a conventional key
    /// (`id`, or any single key ending in `_id`).
    pub fn id(&self) -> Option<&str> {
        self.extra
            .get("id")
            .and_then(|v| v.as_str())
            .or_else(|| {
                self.extra.iter().find_map(|(k, v)| {
                    if k.ends_with("_id") {
                        v.as_str()
                    } else {
                        None
                    }
                })
            })
    }

    pub fn get(&self, key: &str) -> Option<&serde_json::Value> {
        self.extra.get(key)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn list_params_empty_query() {
        let params = ListParams::new();
        assert!(params.to_query().is_empty());
    }

    #[test]
    fn list_params_with_limit_and_cursor() {
        let params = ListParams::new().limit(10).cursor("abc");
        let q = params.to_query();
        assert_eq!(q, vec![("limit", "10".to_string()), ("cursor", "abc".to_string())]);
    }

    #[test]
    fn list_customers_params_email_query() {
        let params = ListCustomersParams::new().email("test@example.com");
        let q = params.to_query();
        assert_eq!(q, vec![("email", "test@example.com".to_string())]);
    }

    #[test]
    fn list_customers_params_combined() {
        let params = ListCustomersParams::new().limit(5).cursor("xyz").email("a@b.com");
        let q = params.to_query();
        assert_eq!(
            q,
            vec![
                ("limit", "5".to_string()),
                ("cursor", "xyz".to_string()),
                ("email", "a@b.com".to_string()),
            ]
        );
    }

    #[test]
    fn address_serialization_skips_none() {
        let addr = Address::default();
        let json = serde_json::to_value(&addr).unwrap();
        assert!(json.as_object().unwrap().is_empty());
    }

    #[test]
    fn address_serialization_with_values() {
        let addr = Address {
            line1: Some("123 Main St".into()),
            city: Some("Lagos".into()),
            country: Some("NG".into()),
            ..Default::default()
        };
        let json = serde_json::to_value(&addr).unwrap();
        assert_eq!(json["line1"], "123 Main St");
        assert_eq!(json["city"], "Lagos");
        assert_eq!(json["country"], "NG");
        assert_eq!(json.get("line2"), None);
    }

    #[test]
    fn money_serialization() {
        let money = Money {
            amount: "29.00".into(),
            currency: "USD".into(),
        };
        let json = serde_json::to_value(&money).unwrap();
        assert_eq!(json["amount"], "29.00");
        assert_eq!(json["currency"], "USD");
    }

    #[test]
    fn flex_object_id_field() {
        let fo = FlexObject {
            extra: {
                let mut m = std::collections::HashMap::new();
                m.insert("id".into(), serde_json::Value::String("cust_123".into()));
                m
            },
        };
        assert_eq!(fo.id(), Some("cust_123"));
    }

    #[test]
    fn flex_object_suffixed_id_field() {
        let fo = FlexObject {
            extra: {
                let mut m = std::collections::HashMap::new();
                m.insert("customer_id".into(), serde_json::Value::String("cust_456".into()));
                m
            },
        };
        assert_eq!(fo.id(), Some("cust_456"));
    }

    #[test]
    fn flex_object_no_id() {
        let fo = FlexObject {
            extra: {
                let mut m = std::collections::HashMap::new();
                m.insert("name".into(), serde_json::Value::String("Ada".into()));
                m
            },
        };
        assert_eq!(fo.id(), None);
    }

    #[test]
    fn flex_object_get() {
        let fo = FlexObject {
            extra: {
                let mut m = std::collections::HashMap::new();
                m.insert("foo".into(), serde_json::Value::String("bar".into()));
                m
            },
        };
        assert_eq!(fo.get("foo"), Some(&serde_json::Value::String("bar".into())));
        assert_eq!(fo.get("missing"), None);
    }

    #[test]
    fn pagination_deserialization() {
        let json = r#"{"next_cursor": "xyz", "has_more": true, "total_count": 42}"#;
        let p: Pagination = serde_json::from_str(json).unwrap();
        assert_eq!(p.next_cursor.as_deref(), Some("xyz"));
        assert!(p.has_more);
        assert_eq!(p.total_count, Some(42));
    }

    #[test]
    fn list_response_deserialization() {
        let json = r#"{"items": [], "pagination": {"has_more": false}}"#;
        let resp: ListResponse<String> = serde_json::from_str(json).unwrap();
        assert!(resp.items.is_empty());
        assert!(!resp.pagination.has_more);
    }
}