use std::sync::Arc;
use crate::error::Result;
use crate::http::Config;
use crate::types::{
list_query, BatchResponse, BatchValidation, CancelEmailResponse, CreateEmailResponse,
DeleteEmailResponse, Email, EmailInsights, EmailListItem, Idempotent, List, ListOptions,
SendEmailOptions, UpdateEmailOptions, UpdateEmailResponse,
};
#[derive(Clone)]
pub struct Emails(pub(crate) Arc<Config>);
impl Emails {
pub async fn send<'a>(
&self,
email: impl Into<Idempotent<&'a SendEmailOptions>>,
) -> Result<CreateEmailResponse> {
let email = email.into();
self.0
.post_with(
&["emails"],
&[],
email.data,
&[("Idempotency-Key", email.idempotency_key.as_deref())],
)
.await
}
pub async fn send_with_idempotency_key(
&self,
email: &SendEmailOptions,
idempotency_key: &str,
) -> Result<CreateEmailResponse> {
self.send(Idempotent {
data: email,
idempotency_key: Some(idempotency_key.to_string()),
})
.await
}
pub async fn get(&self, id: &str) -> Result<Email> {
self.0.get(&["emails", id], &[]).await
}
pub async fn list(&self, options: Option<&ListOptions>) -> Result<List<EmailListItem>> {
self.0.get(&["emails"], &list_query(options)).await
}
pub async fn update(
&self,
id: &str,
changes: &UpdateEmailOptions,
) -> Result<UpdateEmailResponse> {
self.0.patch(&["emails", id], changes).await
}
pub async fn get_insights(&self, id: &str) -> Result<EmailInsights> {
self.0.get(&["emails", id, "insights"], &[]).await
}
pub async fn cancel(&self, id: &str) -> Result<CancelEmailResponse> {
self.0.post_empty(&["emails", id, "cancel"]).await
}
pub async fn delete(&self, id: &str) -> Result<DeleteEmailResponse> {
self.0.delete(&["emails", id]).await
}
}
#[derive(Clone)]
pub struct Batch(pub(crate) Arc<Config>);
impl Batch {
pub async fn send<'a>(
&self,
emails: impl Into<Idempotent<&'a [SendEmailOptions]>>,
) -> Result<BatchResponse> {
self.post(emails.into(), None).await
}
pub async fn send_with_idempotency_key(
&self,
emails: &[SendEmailOptions],
idempotency_key: &str,
) -> Result<BatchResponse> {
let emails = Idempotent {
data: emails,
idempotency_key: Some(idempotency_key.to_string()),
};
self.post(emails, None).await
}
pub async fn send_with_batch_validation<'a>(
&self,
emails: impl Into<Idempotent<&'a [SendEmailOptions]>>,
validation: BatchValidation,
) -> Result<BatchResponse> {
self.post(emails.into(), Some(validation)).await
}
async fn post(
&self,
emails: Idempotent<&[SendEmailOptions]>,
validation: Option<BatchValidation>,
) -> Result<BatchResponse> {
self.0
.post_with(
&["emails", "batch"],
&[],
emails.data,
&[
("Idempotency-Key", emails.idempotency_key.as_deref()),
(
"x-batch-validation",
validation.map(BatchValidation::as_str),
),
],
)
.await
}
}