1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
use crate::clients::ApiClient;
use anyhow::Result;
use reqwest::{header, Url};
use std::time::Duration;
#[derive(Debug)]
pub struct ApiClientBuilder {
base_url: Url,
timeout: Option<Duration>,
user_agent: Option<String>,
bearer_token: Option<String>,
}
impl ApiClientBuilder {
pub fn new(base_url: Url) -> Self {
Self {
base_url,
timeout: None,
user_agent: None,
bearer_token: None,
}
}
pub fn base_url(mut self, base_url: Url) -> Self {
self.base_url = base_url;
self
}
pub fn timeout(mut self, timeout: Option<Duration>) -> Self {
self.timeout = timeout;
self
}
pub fn user_agent(mut self, user_agent: Option<impl Into<String>>) -> Self {
self.user_agent = user_agent.map(|agent| agent.into());
self
}
pub fn bearer_token(mut self, bearer_token: Option<impl Into<String>>) -> Self {
self.bearer_token = bearer_token.map(|token| token.into());
self
}
pub fn build_client(&self) -> Result<reqwest::Client> {
let mut headers = header::HeaderMap::new();
headers.insert(
header::USER_AGENT,
header::HeaderValue::from_str(
self.user_agent
.as_deref()
.unwrap_or("Fiberplane Rust API client"),
)?,
);
if let Some(bearer) = &self.bearer_token {
headers.insert(
header::AUTHORIZATION,
header::HeaderValue::from_str(&format!("Bearer {}", bearer))?,
);
}
let client = reqwest::Client::builder()
.connect_timeout(self.timeout.unwrap_or_else(|| Duration::from_secs(5)))
.default_headers(headers)
.build()?;
Ok(client)
}
pub fn build(self) -> Result<ApiClient> {
let client = self.build_client()?;
let server = self.base_url;
Ok(ApiClient { client, server })
}
}