use crate::core::error::Result;
use async_trait::async_trait;
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::collections::HashMap;
use std::time::Duration;
#[async_trait]
pub trait HttpProvider: Send + Sync {
async fn get<T>(&self, path: &str) -> Result<T>
where
T: DeserializeOwned + Send;
async fn post<T, B>(&self, path: &str, body: &B) -> Result<T>
where
T: DeserializeOwned + Send,
B: Serialize + Send + Sync + ?Sized;
async fn put<T, B>(&self, path: &str, body: &B) -> Result<T>
where
T: DeserializeOwned + Send,
B: Serialize + Send + Sync + ?Sized;
async fn delete(&self, path: &str) -> Result<()>;
async fn post_binary<B>(&self, path: &str, body: &B) -> Result<Vec<u8>>
where
B: Serialize + Send + Sync + ?Sized;
fn set_session_token(&mut self, token: Option<String>);
fn set_timeout(&mut self, timeout: Duration);
fn last_response_metadata(&self) -> Option<ResponseMetadata> {
None
}
}
#[derive(Debug, Clone)]
pub struct ResponseMetadata {
pub status: u16,
pub headers: HashMap<String, String>,
pub elapsed: Duration,
pub size: Option<usize>,
}
impl ResponseMetadata {
pub fn new(status: u16) -> Self {
Self {
status,
headers: HashMap::new(),
elapsed: Duration::from_secs(0),
size: None,
}
}
pub fn with_elapsed(mut self, elapsed: Duration) -> Self {
self.elapsed = elapsed;
self
}
pub fn with_header(mut self, key: String, value: String) -> Self {
self.headers.insert(key, value);
self
}
pub fn with_size(mut self, size: usize) -> Self {
self.size = Some(size);
self
}
}
#[derive(Debug, Clone)]
pub struct NoOpHttpProvider;
#[async_trait]
impl HttpProvider for NoOpHttpProvider {
async fn get<T>(&self, _path: &str) -> Result<T>
where
T: DeserializeOwned + Send,
{
Err(crate::core::error::Error::Network(
"NoOp provider".to_string(),
))
}
async fn post<T, B>(&self, _path: &str, _body: &B) -> Result<T>
where
T: DeserializeOwned + Send,
B: Serialize + Send + Sync + ?Sized,
{
Err(crate::core::error::Error::Network(
"NoOp provider".to_string(),
))
}
async fn put<T, B>(&self, _path: &str, _body: &B) -> Result<T>
where
T: DeserializeOwned + Send,
B: Serialize + Send + Sync + ?Sized,
{
Err(crate::core::error::Error::Network(
"NoOp provider".to_string(),
))
}
async fn delete(&self, _path: &str) -> Result<()> {
Err(crate::core::error::Error::Network(
"NoOp provider".to_string(),
))
}
async fn post_binary<B>(&self, _path: &str, _body: &B) -> Result<Vec<u8>>
where
B: Serialize + Send + Sync + ?Sized,
{
Err(crate::core::error::Error::Network(
"NoOp provider".to_string(),
))
}
fn set_session_token(&mut self, _token: Option<String>) {}
fn set_timeout(&mut self, _timeout: Duration) {}
}