use std::sync::Arc;
use std::time::Duration;
use crate::error::{Error, Result};
use crate::resources::{Batch, Chat, Emails, Events, Knowledge, Payments, Revenue};
use crate::transport::{Async, Executor, Inner};
pub const DEFAULT_BASE_URL: &str = "https://api.hatang.dev";
pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
#[derive(Debug, Default, Clone)]
pub struct HatangBuilder {
api_key: Option<String>,
base_url: Option<String>,
environment: Option<String>,
timeout: Option<Duration>,
user_agent: Option<String>,
http: Option<reqwest::Client>,
}
impl HatangBuilder {
pub fn api_key(mut self, key: impl Into<String>) -> Self {
self.api_key = Some(key.into());
self
}
pub fn base_url(mut self, url: impl Into<String>) -> Self {
self.base_url = Some(url.into());
self
}
pub fn environment(mut self, environment: impl Into<String>) -> Self {
self.environment = Some(environment.into());
self
}
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = Some(timeout);
self
}
pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
self.user_agent = Some(user_agent.into());
self
}
pub fn http_client(mut self, client: reqwest::Client) -> Self {
self.http = Some(client);
self
}
fn inner(self) -> Result<Inner> {
let env = |k: &str| std::env::var(k).ok().filter(|v| !v.is_empty());
let api_key = self
.api_key
.filter(|k| !k.is_empty())
.or_else(|| env("HATANG_API_KEY"))
.ok_or_else(|| {
Error::Config(
r#"Missing API key. Pass it: Hatang::new("ht_123"), or set HATANG_API_KEY"#
.into(),
)
})?;
let base_url = self
.base_url
.or_else(|| env("HATANG_BASE_URL"))
.unwrap_or_else(|| DEFAULT_BASE_URL.into())
.trim_end_matches('/')
.to_string();
let http = match self.http {
Some(http) => http,
None => reqwest::Client::builder()
.timeout(self.timeout.unwrap_or(DEFAULT_TIMEOUT))
.build()
.map_err(|e| Error::Config(format!("HTTP client: {e}")))?,
};
Ok(Inner {
http,
api_key,
base_url,
environment: self.environment.or_else(|| env("HATANG_ENVIRONMENT")),
user_agent: self
.user_agent
.unwrap_or_else(|| format!("hatang-sdk-rust/{VERSION} (rust)")),
})
}
pub fn build(self) -> Result<Hatang> {
Ok(Client::with(Async(Arc::new(self.inner()?))))
}
#[cfg(feature = "blocking")]
#[cfg_attr(docsrs, doc(cfg(feature = "blocking")))]
pub fn build_blocking(self) -> Result<crate::blocking::Hatang> {
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.map_err(|e| Error::Config(format!("runtime: {e}")))?;
Ok(Client::with(crate::transport::Blocking(
Arc::new(self.inner()?),
Arc::new(rt),
)))
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Client<C> {
pub emails: Emails<C>,
pub batch: Batch<C>,
pub knowledge: Knowledge<C>,
pub chat: Chat<C>,
pub payments: Payments<C>,
pub events: Events<C>,
pub revenue: Revenue<C>,
}
impl<C: Executor> Client<C> {
fn with(c: C) -> Self {
Client {
emails: Emails::new(c.clone()),
batch: Batch::new(c.clone()),
knowledge: Knowledge::new(c.clone()),
chat: Chat::new(c.clone()),
payments: Payments::new(c.clone()),
events: Events::new(c.clone()),
revenue: Revenue::new(c),
}
}
}
pub type Hatang = Client<Async>;
impl Hatang {
pub fn new(api_key: impl Into<String>) -> Result<Self> {
Self::builder().api_key(api_key).build()
}
pub fn from_env() -> Result<Self> {
Self::builder().build()
}
pub fn builder() -> HatangBuilder {
HatangBuilder::default()
}
}