use super::async_client::AsyncTransport;
use crate::error::{Error, Result};
use std::future::Future;
use std::time::Duration;
#[derive(Debug, Clone)]
pub struct ReqwestTransport {
client: reqwest::Client,
}
impl ReqwestTransport {
pub fn new() -> Result<Self> {
let client = reqwest::Client::builder()
.user_agent(concat!("hivecomb/", env!("CARGO_PKG_VERSION")))
.build()
.map_err(|e| Error::Rpc(format!("could not build HTTP client: {e}")))?;
Ok(ReqwestTransport { client })
}
pub fn from_client(client: reqwest::Client) -> Self {
ReqwestTransport { client }
}
}
impl AsyncTransport for ReqwestTransport {
fn post_json(
&self,
url: &str,
body: &str,
timeout: Duration,
) -> impl Future<Output = Result<String>> + Send {
let client = self.client.clone();
let url = url.to_string();
let body = body.to_string();
async move {
let response = client
.post(&url)
.header("Content-Type", "application/json")
.timeout(timeout)
.body(body)
.send()
.await
.map_err(|e| Error::Rpc(e.to_string()))?;
response
.text()
.await
.map_err(|e| Error::Rpc(format!("could not read response body: {e}")))
}
}
}
pub fn tokio_sleeper() -> impl Fn(Duration) -> tokio::time::Sleep + Send + Sync + 'static {
tokio::time::sleep
}