use crate::{Response, ResponsePayload, RpcError, RpcReturn};
use serde_json::value::RawValue;
use std::borrow::Borrow;
pub type RpcResult<T, E, ErrResp = Box<RawValue>> = Result<T, RpcError<E, ErrResp>>;
pub type BorrowedRpcResult<'a, E> = RpcResult<&'a RawValue, E, &'a RawValue>;
pub fn transform_response<T, E, ErrResp>(response: Response<T, ErrResp>) -> RpcResult<T, E, ErrResp>
where
ErrResp: RpcReturn,
{
match response {
Response { payload: ResponsePayload::Failure(err_resp), .. } => {
Err(RpcError::err_resp(err_resp))
}
Response { payload: ResponsePayload::Success(result), .. } => Ok(result),
}
}
pub fn transform_result<T, E, ErrResp>(
response: Result<Response<T, ErrResp>, E>,
) -> Result<T, RpcError<E, ErrResp>>
where
ErrResp: RpcReturn,
{
match response {
Ok(resp) => transform_response(resp),
Err(e) => Err(RpcError::Transport(e)),
}
}
pub fn try_deserialize_ok<J, T, E, ErrResp>(
result: RpcResult<J, E, ErrResp>,
) -> RpcResult<T, E, ErrResp>
where
J: Borrow<RawValue>,
T: RpcReturn,
ErrResp: RpcReturn,
{
let json = result?;
let json = json.borrow().get();
trace!(ty=%std::any::type_name::<T>(), %json, "deserializing response");
serde_json::from_str(json)
.inspect(|response| trace!(?response, "deserialized response"))
.inspect_err(|err| trace!(?err, "failed to deserialize response"))
.map_err(|err| RpcError::deser_err(err, json))
}