Skip to main content

seher/openrouter/
client.rs

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