oss_api_client/api_client/
oss_file_api_client.rs1use anyhow::anyhow;
2use reqwest::header::{HeaderMap, HeaderValue};
3use robotech::api_client::{ApiClient, ApiClientError};
4use robotech::cst::user_id_cst::USER_ID_HEADER_NAME;
5use robotech::ro::Ro;
6use std::fmt::Display;
7use std::ops::{Deref, DerefMut};
8use std::string::ToString;
9
10#[derive(Debug)]
12pub struct OssFileApiClient {
13 pub api_client: ApiClient,
14}
15
16impl Deref for OssFileApiClient {
17 type Target = ApiClient;
18
19 fn deref(&self) -> &Self::Target {
20 &self.api_client
21 }
22}
23impl DerefMut for OssFileApiClient {
24 fn deref_mut(&mut self) -> &mut Self::Target {
25 &mut self.api_client
26 }
27}
28
29impl OssFileApiClient {
30 pub async fn upload_file(
40 &self,
41 bucket: &str,
42 file_path: &str,
43 file_name: &str,
44 current_user_id: u64,
45 ) -> Result<Ro<serde_json::Value>, ApiClientError> {
46 let url = format!("/oss/file/upload/{}", bucket);
47 let form = reqwest::multipart::Form::new()
48 .file("file", file_path)
49 .await
50 .map_err(|e| ApiClientError::ReadFile(url.clone(), e))?
51 .text("fileName", file_name.to_string());
52 let mut headers = HeaderMap::new();
53 headers.insert(
54 USER_ID_HEADER_NAME,
55 HeaderValue::from_str(¤t_user_id.to_string().as_str())
56 .map_err(|e| anyhow!("current_user_id: {}", e))?,
57 );
58
59 self.multipart(&url, form, Some(headers), None).await
60 }
61
62 pub async fn upload_file_content(
73 &self,
74 bucket: &str,
75 file_name: &str,
76 data: Vec<u8>,
77 current_user_id: u64,
78 ) -> Result<Ro<serde_json::Value>, ApiClientError> {
79 let url = format!("/oss/file/upload/{}", bucket);
80 let part = reqwest::multipart::Part::bytes(data).file_name(file_name.to_string());
81 let form = reqwest::multipart::Form::new().part("file", part);
82 let mut headers = HeaderMap::new();
83 headers.insert(
84 USER_ID_HEADER_NAME,
85 HeaderValue::from_str(¤t_user_id.to_string().as_str())
86 .map_err(|e| anyhow!("current_user_id: {}", e))?,
87 );
88 self.multipart(&url, form, Some(headers), None).await
89 }
90
91 pub async fn download_file(
101 &self,
102 obj_id: impl Display,
103 current_user_id: u64,
104 ) -> Result<Vec<u8>, ApiClientError> {
105 let url = format!("/oss/file/download/{}", obj_id);
106 let mut headers = HeaderMap::new();
107 headers.insert(
108 USER_ID_HEADER_NAME,
109 HeaderValue::from_str(¤t_user_id.to_string().as_str())
110 .map_err(|e| anyhow!("current_user_id: {}", e))?,
111 );
112 self.get_bytes::<()>(&url, None, Some(headers), None).await
113 }
114
115 pub async fn preview_file(
125 &self,
126 obj_id: impl Display,
127 current_user_id: u64,
128 ) -> Result<Vec<u8>, ApiClientError> {
129 let url = format!("/oss/file/preview/{}", obj_id);
130 let mut headers = HeaderMap::new();
131 headers.insert(
132 USER_ID_HEADER_NAME,
133 HeaderValue::from_str(¤t_user_id.to_string().as_str())
134 .map_err(|e| anyhow!("current_user_id: {}", e))?,
135 );
136 self.get_bytes::<()>(&url, None, Some(headers), None).await
137 }
138}