1use crate::res::ApiError;
2pub mod prelude;
4pub mod res;
5pub mod node;
7pub mod panel;
8pub mod tunnel;
9pub mod user;
10pub mod util;
11
12use dotenvy::dotenv;
13use std::env;
14
15pub struct ChmlApi {
17 pub base_url: String,
18 pub token: Option<String>,
19 pub client: reqwest::Client,
20}
21
22impl ChmlApi {
23 pub fn new(base_url: &str) -> Self {
24 ChmlApi {
25 base_url: base_url.to_string(),
26 token: None,
27 client: reqwest::Client::new(),
28 }
29 }
30
31 pub fn from_env() -> Result<Self, std::env::VarError> {
32 dotenv().ok();
33 let base_url = env::var("CHML_API_BASE_URL")?;
34 let token = env::var("CHML_API_TOKEN")?;
35 Ok(Self {
36 base_url,
37 token: Some(token),
38 client: reqwest::Client::new(),
39 })
40 }
41
42 pub fn new_with_token(base_url: &str, token: &str) -> Self {
43 ChmlApi {
44 base_url: base_url.to_string(),
45 token: Some(token.to_string()),
46 client: reqwest::Client::new(),
47 }
48 }
49
50 pub fn endpoint(&self, path: &str) -> String {
51 format!("{}{}", self.base_url, path)
52 }
53
54 pub fn set_token(&mut self, token: &str) {
55 self.token = Some(token.to_string());
56 }
57
58 pub fn get_token(&self) -> Result<&str, ApiError> {
59 self.token.as_deref().ok_or(ApiError::NoToken)
60 }
61}
62
63pub fn init_logger() {
64 let subscriber = tracing_subscriber::FmtSubscriber::builder()
65 .with_env_filter("debug") .finish();
67 tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed");
68}