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;
#[derive(Debug, Clone)]
pub struct Files {
inner: Arc<Inner>,
}
impl Files {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
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
}
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
}
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")
);
}
}