use std::future::Future;
use response::PostalData;
use serde::Serialize;
pub mod error;
pub mod message;
pub mod response;
use crate::error::PostalClientError;
use crate::message::PostalMessage;
use crate::response::{MessagesData, PostalResponse};
#[derive(Debug, Clone)]
pub struct PostalClient {
client: reqwest::Client,
host: String,
api_key: String,
}
impl PostalClient {
pub fn new(host: String, api_key: String) -> Self {
let client = reqwest::Client::new();
Self {
client,
host,
api_key,
}
}
fn send_request<'a, T: Serialize + 'a>(
&'a self,
controller: &'a str,
action: &'a str,
parameters: T,
) -> std::pin::Pin<Box<impl Future<Output = Result<MessagesData, PostalClientError>> + 'a>>
{
Box::pin(async move {
let response = self
.client
.post(format!("{}/api/v1/{controller}/{action}", self.host))
.json(¶meters)
.header("X-Server-API-Key", &self.api_key)
.send()
.await?;
let res_json: PostalResponse = response.json().await?;
match res_json.data {
PostalData::Success(res) => Ok(res),
PostalData::Error(err) => Err(err.code.into()),
}
})
}
pub fn send_message<'a>(
&'a self,
message: PostalMessage<'a>,
) -> std::pin::Pin<Box<impl Future<Output = Result<MessagesData, PostalClientError>> + 'a>>
{
self.send_request("send", "message", message)
}
}