Skip to main content

timeweb_rs/
client.rs

1//! Idiomatic entry point for building an authenticated API configuration.
2
3use crate::apis::configuration::Configuration;
4
5/// Default base URL of the Timeweb Cloud API.
6pub const DEFAULT_BASE_URL: &str = "https://api.timeweb.cloud";
7
8/// Builds a [`Configuration`] authenticated with a Timeweb Cloud JWT token.
9///
10/// The token is issued in the Timeweb Cloud control panel under the
11/// "API и Terraform" section. It is sent as a `Bearer` `Authorization` header
12/// on every request made with the returned configuration.
13///
14/// Pass the configuration to any function in [`crate::apis`]:
15///
16/// ```no_run
17/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
18/// use timeweb_rs::apis::account_api;
19///
20/// let config = timeweb_rs::authenticated("your-jwt-token");
21/// let status = account_api::get_account_status(&config).await?;
22/// println!("{status:#?}");
23/// # Ok(())
24/// # }
25/// ```
26#[must_use]
27pub fn authenticated(token: impl Into<String>) -> Configuration {
28    Configuration {
29        bearer_access_token: Some(token.into()),
30        user_agent: Some(concat!("timeweb-rs/", env!("CARGO_PKG_VERSION")).to_string()),
31        ..Configuration::default()
32    }
33}
34
35/// Builds an authenticated [`Configuration`] targeting a custom base URL.
36///
37/// Useful for testing against a mock server or a proxy. For production use
38/// prefer [`authenticated`], which targets [`DEFAULT_BASE_URL`].
39#[must_use]
40pub fn authenticated_with_base_url(
41    token: impl Into<String>,
42    base_url: impl Into<String>
43) -> Configuration {
44    Configuration {
45        base_path: base_url.into(),
46        ..authenticated(token)
47    }
48}
49
50#[cfg(test)]
51mod tests {
52    use super::{DEFAULT_BASE_URL, authenticated, authenticated_with_base_url};
53
54    #[test]
55    fn authenticated_sets_bearer_token_and_default_base_url() {
56        let config = authenticated("jwt-token");
57        assert_eq!(config.bearer_access_token.as_deref(), Some("jwt-token"));
58        assert_eq!(config.base_path, DEFAULT_BASE_URL);
59    }
60
61    #[test]
62    fn authenticated_sets_crate_user_agent() {
63        let config = authenticated("jwt-token");
64        let user_agent = config.user_agent.expect("user agent is set");
65        assert!(user_agent.starts_with("timeweb-rs/"));
66    }
67
68    #[test]
69    fn authenticated_with_base_url_overrides_base_path() {
70        let config = authenticated_with_base_url("jwt-token", "http://localhost:8080");
71        assert_eq!(config.base_path, "http://localhost:8080");
72        assert_eq!(config.bearer_access_token.as_deref(), Some("jwt-token"));
73    }
74}