use http_body_util::BodyExt as _;
use rustolio_utils::{
bytes::encoding::{decode_from_hyper_stream, encode_to_bytes},
http::{self, StatusCode},
prelude::*,
threadsafe::Threadsafe,
};
use crate::ServerFnError;
pub async fn decode_rpc_body<B, Msg>(req: http::Request<B>) -> Result<Msg, ServerFnError>
where
B: hyper::body::Body + Unpin + Threadsafe,
Msg: Decode + Threadsafe,
{
let stream = req.into_body().into_data_stream();
let Ok(msg) = decode_from_hyper_stream::<_, _, B>(stream).await else {
return Err(ServerFnError::http_error(
StatusCode::BAD_REQUEST,
"Failed to parse request body",
));
};
Ok(msg)
}
pub fn encode_rpc_response<R, E>(res: Result<R, ServerFnError<E>>) -> http::Response
where
R: Encode,
E: Encode,
{
if let Err(ServerFnError::HttpError(status, msg)) = res {
return http::Response::builder()
.status(status)
.text(msg)
.build()
.unwrap();
}
let Ok(body) = encode_to_bytes(&res) else {
return http::Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.text("Failed to serialize response")
.build()
.unwrap();
};
http::Response::builder().bytes(body).build().unwrap()
}