use tosca::response::{InfoResponse, OkResponse, SerialResponse};
use reqwest::Response as ReqwestResponse;
use serde::{Serialize, de::DeserializeOwned};
use crate::error::{Error, ErrorKind, Result};
async fn json_response<T>(response: ReqwestResponse) -> Result<T>
where
T: Serialize + DeserializeOwned,
{
response
.json::<T>()
.await
.map_err(|e| Error::new(ErrorKind::JsonResponse, format!("Json error caused by {e}")))
}
pub struct OkResponseParser(ReqwestResponse);
impl OkResponseParser {
pub async fn parse_body(self) -> Result<OkResponse> {
json_response::<OkResponse>(self.0).await
}
pub(crate) const fn new(response: ReqwestResponse) -> Self {
Self(response)
}
}
pub struct SerialResponseParser(ReqwestResponse);
impl SerialResponseParser {
pub async fn parse_body<T: Serialize + DeserializeOwned>(self) -> Result<SerialResponse<T>> {
json_response::<SerialResponse<T>>(self.0).await
}
pub(crate) const fn new(response: ReqwestResponse) -> Self {
Self(response)
}
}
pub struct InfoResponseParser(ReqwestResponse);
impl InfoResponseParser {
pub async fn parse_body(self) -> Result<InfoResponse> {
json_response::<InfoResponse>(self.0).await
}
pub(crate) const fn new(response: ReqwestResponse) -> Self {
Self(response)
}
}
#[cfg(feature = "stream")]
pub struct StreamResponse(ReqwestResponse);
#[cfg(feature = "stream")]
impl StreamResponse {
pub fn open_stream(self) -> impl futures_util::Stream<Item = Result<bytes::Bytes>> {
use futures_util::TryStreamExt;
self.0.bytes_stream().map_err(|e| {
Error::new(
ErrorKind::StreamResponse,
format!("Stream error caused by {e}"),
)
})
}
pub(crate) const fn new(response: ReqwestResponse) -> Self {
Self(response)
}
}
pub enum Response {
Skipped,
OkBody(OkResponseParser),
SerialBody(SerialResponseParser),
InfoBody(InfoResponseParser),
#[cfg(feature = "stream")]
StreamBody(StreamResponse),
}