delopay 0.4.0

Official Rust SDK for the DeloPay payments API
Documentation
//! The `cards` resource: card records and BIN lookups. Open request and
//! response shapes — see the API reference.

use std::sync::Arc;

use serde_json::Value;

use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::Result;
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;

/// The `cards` resource, obtained via [`crate::Delopay::cards`].
#[derive(Debug, Clone)]
pub struct Cards {
    inner: Arc<Inner>,
}

impl Cards {
    pub(crate) fn new(inner: Arc<Inner>) -> Self {
        Self { inner }
    }

    /// Create a card record.
    pub async fn create(&self, params: &Value) -> Result<Value> {
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, "/cards/create", Some(&body), &[], None)
            .await
    }

    /// Update a card record.
    pub async fn update(&self, params: &Value) -> Result<Value> {
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, "/cards/update", Some(&body), &[], None)
            .await
    }

    /// Retrieve card info by BIN (bank identification number).
    pub async fn retrieve(&self, bin: &str) -> Result<Value> {
        let path = format!("/cards/{}", encode_segment(bin));
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }
}

#[cfg(test)]
mod tests {
    use crate::http::mock::{Step, client_with};
    use serde_json::json;

    #[tokio::test]
    async fn card_operations_hit_their_documented_paths() {
        let (client, mock) = client_with(vec![
            Step::ok(r#"{"card_id":"card_1"}"#),
            Step::ok(r#"{"card_id":"card_1"}"#),
            Step::ok(r#"{"card_network":"Visa"}"#),
        ]);
        let cards = client.cards();
        let body = json!({"k": "v"});
        cards.create(&body).await.unwrap();
        cards.update(&body).await.unwrap();
        cards.retrieve("424242").await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            (seen[0].method, seen[0].url.as_str()),
            ("POST", "https://api.test/cards/create")
        );
        assert_eq!(
            (seen[1].method, seen[1].url.as_str()),
            ("POST", "https://api.test/cards/update")
        );
        assert_eq!(
            (seen[2].method, seen[2].url.as_str()),
            ("GET", "https://api.test/cards/424242")
        );
    }
}