Skip to main content

zai_rs/file/
content.rs

1use crate::client::http::HttpClient;
2
3/// File content request (GET /paas/v4/files/{file_id}/content)
4pub struct FileContentRequest {
5    pub key: String,
6    url: String,
7    _body: (),
8}
9
10impl FileContentRequest {
11    pub fn new(key: String, file_id: impl Into<String>) -> Self {
12        let url = format!(
13            "https://open.bigmodel.cn/api/paas/v4/files/{}/content",
14            file_id.into()
15        );
16        Self {
17            key,
18            url,
19            _body: (),
20        }
21    }
22
23    /// Send the request and return raw bytes of the file content.
24    pub async fn send(&self) -> crate::ZaiResult<Vec<u8>> {
25        let resp: reqwest::Response = self.get().await?;
26
27        let status = resp.status();
28
29        if !status.is_success() {
30            let text = resp.text().await.unwrap_or_default();
31
32            return Err(crate::client::error::ZaiError::from_api_response(
33                status.as_u16(),
34                0,
35                text,
36            ));
37        }
38
39        let bytes = resp.bytes().await?;
40        Ok(bytes.to_vec())
41    }
42
43    /// It will create parent directories if missing.
44    /// Returns the number of bytes written.
45    pub async fn send_to<P: AsRef<std::path::Path>>(&self, path: P) -> crate::ZaiResult<usize> {
46        let bytes = self.send().await?;
47
48        let p = path.as_ref();
49
50        if let Some(parent) = p.parent()
51            && !parent.as_os_str().is_empty()
52        {
53            std::fs::create_dir_all(parent)?;
54        }
55        use std::io::Write;
56        let mut f = std::fs::File::create(p)?;
57        f.write_all(&bytes)?;
58        Ok(bytes.len())
59    }
60}
61
62impl HttpClient for FileContentRequest {
63    type Body = ();
64    type ApiUrl = String;
65    type ApiKey = String;
66
67    fn api_url(&self) -> &Self::ApiUrl {
68        &self.url
69    }
70    fn api_key(&self) -> &Self::ApiKey {
71        &self.key
72    }
73    fn body(&self) -> &Self::Body {
74        &self._body
75    }
76}