use serde::de::DeserializeOwned;
use crate::error::{Error, Result};
use crate::transport::{Request, Response};
type Read<T> = dyn Fn(Result<Response>) -> Result<T> + Send + Sync;
pub struct Call<T> {
pub request: Request,
read: Box<Read<T>>,
}
impl<T> std::fmt::Debug for Call<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Call")
.field("request", &self.request)
.finish_non_exhaustive()
}
}
impl<T> Call<T> {
pub(crate) fn new(
request: Request,
read: impl Fn(Result<Response>) -> Result<T> + Send + Sync + 'static,
) -> Self {
Call {
request,
read: Box::new(read),
}
}
pub fn parse(&self, response: Response) -> Result<T> {
let result = if (200..300).contains(&response.status) {
Ok(response)
} else {
Err(Error::from_status(
response.status,
Some(&self.request.path),
&response.body,
))
};
self.read(result)
}
pub fn read(&self, result: Result<Response>) -> Result<T> {
(self.read)(result)
}
pub(crate) fn into_parts(self) -> (Request, Box<Read<T>>) {
(self.request, self.read)
}
pub(crate) fn map<U>(self, then: impl Fn(T) -> Result<U> + Send + Sync + 'static) -> Call<U>
where
T: 'static,
{
let read = self.read;
Call::new(self.request, move |result| read(result).and_then(&then))
}
}
impl<T: DeserializeOwned + 'static> Call<T> {
pub(crate) fn json(request: Request) -> Self {
let path = request.path.clone();
Call::new(request, move |result| {
serde_json::from_slice(&result?.body)
.map_err(|e| Error::malformed(format!("unexpected answer: {e}"), Some(&path)))
})
}
}
impl Call<()> {
pub(crate) fn empty(request: Request) -> Self {
Call::new(request, |result| result.map(|_| ()))
}
}
impl Call<Vec<u8>> {
pub(crate) fn bytes(request: Request) -> Self {
Call::new(request, |result| result.map(|response| response.body))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ErrorKind;
fn response(status: u16, body: &str) -> Response {
Response {
status,
headers: Vec::new(),
body: body.as_bytes().to_vec(),
}
}
#[test]
fn reads_a_status_like_the_transports() {
let call: Call<Vec<u32>> = Call::json(Request::get("/x"));
assert_eq!(call.parse(response(200, "[1,2]")).unwrap(), vec![1, 2]);
let refused = call.parse(response(401, r#"{"message":"expired"}"#));
let refused = refused.unwrap_err();
assert_eq!(refused.kind(), ErrorKind::Unauthorized);
assert_eq!(refused.to_string(), "expired");
assert_eq!(refused.path(), Some("/x"));
let malformed = call.parse(response(200, "nope")).unwrap_err();
assert_eq!(malformed.kind(), ErrorKind::MalformedResponse);
assert_eq!(malformed.path(), Some("/x"));
assert_eq!(
call.read(Err(Error::transport("offline")))
.unwrap_err()
.kind(),
ErrorKind::Transport
);
}
#[test]
fn maps_an_answer() {
let call = Call::json(Request::get("/count")).map(|n: u64| Ok(n * 2));
assert_eq!(call.parse(response(200, "21")).unwrap(), 42);
assert!(
Call::empty(Request::get("/"))
.parse(response(204, ""))
.is_ok()
);
assert_eq!(
Call::bytes(Request::get("/"))
.parse(response(200, "ab"))
.unwrap(),
b"ab".to_vec()
);
}
#[test]
fn never_prints_a_token() {
let call = Call::empty(Request::get("/x").bearer("secret"));
let printed = format!("{call:?}");
assert!(printed.contains("/x"));
assert!(!printed.contains("secret"));
}
}