delopay 0.2.0

Official Rust SDK for the DeloPay payments API
Documentation
//! The `files` resource: upload and manage files (e.g. dispute evidence).
//! 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 `files` resource, obtained via [`crate::Delopay::files`].
#[derive(Debug, Clone)]
pub struct Files {
    inner: Arc<Inner>,
}

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

    /// Upload a file record. The returned file ID can be referenced from
    /// dispute evidence fields.
    pub async fn create(&self, params: &Value) -> Result<Value> {
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, "/files", Some(&body), &[], None)
            .await
    }

    /// Retrieve a file by ID.
    pub async fn retrieve(&self, file_id: &str) -> Result<Value> {
        let path = format!("/files/{}", encode_segment(file_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// Delete a file by ID.
    pub async fn delete(&self, file_id: &str) -> Result<Value> {
        let path = format!("/files/{}", encode_segment(file_id));
        self.inner
            .request(HttpMethod::Delete, &path, None, &[], None)
            .await
    }
}

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

    #[tokio::test]
    async fn file_operations_hit_their_documented_paths() {
        let (client, mock) = client_with(vec![
            Step::ok(r#"{"file_id":"file_1"}"#),
            Step::ok(r#"{"file_id":"file_1"}"#),
            Step::ok(r#"{"deleted":true}"#),
        ]);
        let files = client.files();
        files
            .create(&json!({"purpose": "dispute_evidence"}))
            .await
            .unwrap();
        files.retrieve("file_1").await.unwrap();
        files.delete("file_1").await.unwrap();

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