Skip to main content

deepinfra_client_rs/
client.rs

1use std::env;
2
3use bon::bon;
4use http::{HeaderMap, HeaderValue};
5use reqwest::Client;
6use thiserror::Error;
7
8const APP_USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"));
9
10/// A client for interacting with the DeepInfra API.
11///
12/// This struct encapsulates an HTTP client with default settings and headers required for authentication.
13#[derive(Clone, Debug)]
14pub struct DeepinfraClient {
15    /// The underlying HTTP client used for sending requests.
16    pub(crate) client: Client,
17}
18
19/// Errors that can occur when building a DeepinfraClient.
20#[derive(Error, Debug)]
21pub enum DeepinfraClientBuilderError {
22    /// Indicates that building the HTTP client failed.
23    #[error("Could not build client {0}")]
24    ReqwestError(#[from] reqwest::Error),
25    /// Indicates that an invalid header value was provided.
26    #[error("Invalid header value {0}")]
27    InvalidHeaderValue(#[from] http::header::InvalidHeaderValue),
28}
29
30#[bon]
31impl DeepinfraClient {
32    /// Creates a new instance of DeepinfraClient.
33    ///
34    /// # Example
35    ///
36    /// ```
37    /// use deepinfra_client_rs::client::DeepinfraClient;
38    ///
39    /// fn main() -> Result<(), Box<dyn std::error::Error>> {
40    ///     let token = "your_api_token";
41    ///     let client = DeepinfraClient::new(token)?;
42    ///     // Use client for further API calls...
43    ///     Ok(())
44    /// }
45    /// ```
46    #[builder]
47    pub fn new(token: &str) -> Result<Self, DeepinfraClientBuilderError> {
48        // Create headers with authorization token.
49        let mut headers = HeaderMap::new();
50        let bearer = format!("Bearer {token}");
51        headers.insert("Authorization", HeaderValue::from_str(&bearer)?);
52
53        // Create a client with default headers and user agent.
54        let client = Client::builder()
55            .default_headers(headers)
56            .user_agent(APP_USER_AGENT)
57            .build()?;
58
59        // Return the constructed DeepinfraClient.
60        Ok(DeepinfraClient { client })
61    }
62}