use longbridge_oauth::OAuth;
use crate::HttpClientError;
fn env_var(suffix: &str) -> Option<String> {
std::env::var(format!("LONGBRIDGE_{suffix}"))
.ok()
.or_else(|| std::env::var(format!("LONGPORT_{suffix}")).ok())
}
fn env_var_required(suffix: &str) -> Result<String, HttpClientError> {
env_var(suffix).ok_or_else(|| HttpClientError::MissingEnvVar {
name: format!("LONGBRIDGE_{suffix}"),
})
}
#[derive(Debug, Clone)]
pub enum AuthConfig {
ApiKey {
app_key: String,
app_secret: String,
access_token: String,
},
OAuth(OAuth),
}
#[derive(Debug, Clone)]
pub struct HttpClientConfig {
pub(crate) http_url: Option<String>,
pub(crate) auth: AuthConfig,
}
impl HttpClientConfig {
pub fn from_apikey(
app_key: impl Into<String>,
app_secret: impl Into<String>,
access_token: impl Into<String>,
) -> Self {
let _ = dotenv::dotenv();
Self {
http_url: env_var("HTTP_URL"),
auth: AuthConfig::ApiKey {
app_key: app_key.into(),
app_secret: app_secret.into(),
access_token: access_token.into(),
},
}
}
pub fn from_oauth(oauth: OAuth) -> Self {
let _ = dotenv::dotenv();
Self {
http_url: env_var("HTTP_URL"),
auth: AuthConfig::OAuth(oauth),
}
}
pub fn from_apikey_env() -> Result<Self, HttpClientError> {
let _ = dotenv::dotenv();
let app_key = env_var_required("APP_KEY")?;
let app_secret = env_var_required("APP_SECRET")?;
let access_token = env_var_required("ACCESS_TOKEN")?;
Ok(Self {
http_url: env_var("HTTP_URL"),
auth: AuthConfig::ApiKey {
app_key,
app_secret,
access_token,
},
})
}
#[must_use]
pub fn http_url(self, url: impl Into<String>) -> Self {
Self {
http_url: Some(url.into()),
..self
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_httpclient_config_new() {
let config = HttpClientConfig::from_apikey("app-key", "app-secret", "access-token");
match &config.auth {
AuthConfig::ApiKey {
app_key,
app_secret,
access_token,
} => {
assert_eq!(app_key, "app-key");
assert_eq!(app_secret, "app-secret");
assert_eq!(access_token, "access-token");
}
_ => panic!("Expected ApiKey auth config"),
}
assert_eq!(config.http_url, None);
}
#[test]
fn test_httpclient_config_http_url() {
let config = HttpClientConfig::from_apikey("app-key", "app-secret", "access-token")
.http_url("https://custom.example.com");
assert_eq!(
config.http_url,
Some("https://custom.example.com".to_string())
);
}
}