Skip to main content

seher/zai/
client.rs

1use std::time::Duration;
2
3use super::types::ZaiUsageResponse;
4
5const DEFAULT_QUOTA_URL: &str = "https://api.z.ai/api/paas/quota/limit";
6
7pub struct ZaiClient;
8
9impl ZaiClient {
10    /// # Errors
11    ///
12    /// Returns an error if the API request fails or the response cannot be parsed.
13    pub async fn fetch_quota(
14        api_key: &str,
15        quota_url: Option<&str>,
16    ) -> Result<ZaiUsageResponse, Box<dyn std::error::Error>> {
17        let url = quota_url.unwrap_or(DEFAULT_QUOTA_URL);
18        let client = Self::build_client()?;
19        let response = client
20            .get(url)
21            .header("Authorization", format!("Bearer {api_key}"))
22            .header("Accept", "application/json")
23            .send()
24            .await?;
25
26        let status = response.status();
27        if !status.is_success() {
28            let body = response.text().await.unwrap_or_default();
29            return Err(format!("Z.AI API error {status}: {body}").into());
30        }
31
32        let quota: ZaiUsageResponse = response.json().await?;
33        Ok(quota)
34    }
35
36    fn build_client() -> Result<reqwest::Client, reqwest::Error> {
37        reqwest::Client::builder()
38            .timeout(Duration::from_secs(30))
39            .build()
40    }
41}