use vonage_core::{Result, HttpConfig, Auth};
use vonage_sms::{SmsClient, SmsRequest, SmsResponse};
use crate::builder::VonageBuilder;
pub struct Vonage {
auth: Box<dyn Auth + Send + Sync>,
sms_client: SmsClient,
}
impl std::fmt::Debug for Vonage {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Vonage")
.field("sms_client", &self.sms_client)
.finish()
}
}
impl Vonage {
pub fn new<A: Auth + Clone + Send + Sync + 'static>(auth: A) -> Result<Self> {
Self::with_config(auth, HttpConfig::default())
}
pub fn with_config<A: Auth + Clone + Send + Sync + 'static>(
auth: A,
config: HttpConfig
) -> Result<Self> {
let sms_client = SmsClient::with_config(config.clone())?;
Ok(Self {
auth: Box::new(auth),
sms_client,
})
}
pub fn builder() -> VonageBuilder {
VonageBuilder::new()
}
pub fn sms(&self) -> SmsService<'_> {
SmsService {
client: &self.sms_client,
auth: self.auth.as_ref(),
}
}
}
pub struct SmsService<'a> {
client: &'a SmsClient,
auth: &'a dyn Auth,
}
impl<'a> std::fmt::Debug for SmsService<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SmsService")
.field("client", &self.client)
.finish()
}
}
impl<'a> SmsService<'a> {
pub async fn send(&self, request: &SmsRequest) -> Result<SmsResponse> {
self.client.send(self.auth, request).await
}
pub async fn send_text(
&self,
from: impl Into<String>,
to: impl Into<String>,
text: impl Into<String>,
) -> Result<SmsResponse> {
let request = SmsRequest::text(from, to, text);
self.send(&request).await
}
}
#[cfg(test)]
mod tests {
use super::*;
use vonage_core::BasicAuth;
#[test]
fn test_vonage_client_creation() {
let auth = BasicAuth::new("test_key", "test_secret");
let vonage = Vonage::new(auth);
assert!(vonage.is_ok());
}
#[test]
fn test_vonage_builder() {
use vonage_core::Region;
use std::time::Duration;
let auth = BasicAuth::new("test_key", "test_secret");
let vonage = Vonage::builder()
.region(Region::EuWest)
.timeout(Duration::from_secs(60))
.build(auth);
assert!(vonage.is_ok());
}
#[test]
fn test_sms_service_access() {
let auth = BasicAuth::new("test_key", "test_secret");
let vonage = Vonage::new(auth).unwrap();
let _sms_service = vonage.sms();
}
}