1use reqwest::{header, Client};
2use std::time::Duration;
3
4const DEFAULT_TIMEOUT: u64 = 30;
5
6pub struct SplaClient {
7 pub(crate) client: Client,
8 pub base_url: String,
9}
10
11impl SplaClient {
12 pub fn new() -> Result<Self, Box<dyn std::error::Error>> {
13 let base_url = std::env::var("DEFAULT_BASE_URL")
14 .unwrap_or_else(|_| "https://spla3.yuu26.com/api".to_string());
15 Self::new_with_base_url(base_url)
16 }
17
18 pub fn new_with_base_url(base_url: String) -> Result<Self, Box<dyn std::error::Error>> {
19 let mut headers = header::HeaderMap::new();
20 headers.insert(
21 header::USER_AGENT,
22 header::HeaderValue::from_static("SplaClient/0.1"),
23 );
24
25 let client = Client::builder()
26 .timeout(Duration::from_secs(DEFAULT_TIMEOUT))
27 .default_headers(headers)
28 .build()?;
29
30 Ok(Self {
31 client,
32 base_url: base_url.to_string(),
33 })
34 }
35
36 pub(crate) fn _build_url(&self, endpoint: &str) -> String {
37 format!(
38 "{}/{}",
39 self.base_url.trim_end_matches('/'),
40 endpoint.trim_start_matches('/')
41 )
42 }
43}
44
45#[cfg(test)]
46mod tests {
47 use super::*;
48
49 #[test]
50 fn test_new_client() {
51 let client = SplaClient::new();
52 assert!(client.is_ok());
53 }
54
55 #[test]
56 fn test_new_client_with_custom_base_url() {
57 let base_url = "https://custom.api.com".to_string();
58 let client = SplaClient::new_with_base_url(base_url.clone());
59 assert!(client.is_ok());
60 assert_eq!(client.unwrap().base_url, base_url.clone());
61 }
62}