use std::collections::BTreeMap;
use std::fmt;
use bytes::Bytes;
use http::{HeaderMap, Method, StatusCode};
use super::error::Error;
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct TmfRequest {
pub method: Method,
pub url: String,
pub query: BTreeMap<String, String>,
pub headers: HeaderMap,
pub body: Option<Bytes>,
}
impl TmfRequest {
pub fn new(method: Method, url: impl Into<String>) -> Self {
Self {
method,
url: url.into(),
query: BTreeMap::new(),
headers: HeaderMap::new(),
body: None,
}
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct TmfResponse {
pub status: StatusCode,
pub headers: HeaderMap,
pub body: Bytes,
}
impl TmfResponse {
#[must_use]
pub fn new(status: StatusCode, headers: HeaderMap, body: Bytes) -> Self {
Self {
status,
headers,
body,
}
}
#[must_use]
pub fn header_count(&self, name: &str) -> Option<usize> {
self.headers.get(name)?.to_str().ok()?.parse().ok()
}
#[must_use]
pub fn total_count(&self) -> Option<usize> {
self.header_count("x-total-count")
}
#[must_use]
pub fn result_count(&self) -> Option<usize> {
self.header_count("x-result-count")
}
}
#[async_trait::async_trait]
pub trait Transport: Send + Sync {
async fn execute(&self, request: TmfRequest) -> Result<TmfResponse, Error>;
}
#[async_trait::async_trait]
impl<T: Transport + ?Sized> Transport for &T {
async fn execute(&self, request: TmfRequest) -> Result<TmfResponse, Error> {
(**self).execute(request).await
}
}
#[async_trait::async_trait]
impl<T: Transport + ?Sized> Transport for std::sync::Arc<T> {
async fn execute(&self, request: TmfRequest) -> Result<TmfResponse, Error> {
(**self).execute(request).await
}
}
#[derive(Debug)]
pub struct TransportError(Box<dyn std::error::Error + Send + Sync>);
impl TransportError {
pub fn new(error: impl Into<Box<dyn std::error::Error + Send + Sync>>) -> Self {
Self(error.into())
}
}
impl fmt::Display for TransportError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
impl std::error::Error for TransportError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(self.0.as_ref())
}
}