use super::App;
use hyper::{
body::{to_bytes, Bytes},
Body, Method, Request, Response,
};
use serde::{de::DeserializeOwned, Serialize};
const LOCAL: ([u8; 4], u16) = ([127, 0, 0, 1], 4321);
#[inline]
fn request(m: Method, path: &str) -> Request<Body> {
assert!(path.starts_with('/'));
Request::builder()
.method(m)
.uri(format!("http://testclient{}", path))
.body(Body::empty())
.unwrap()
}
pub struct Client {
pub(super) app: App,
}
impl Client {
pub fn call<'a>(&'a self, method: Method, path: &str) -> Call<'a> {
Call {
app: &self.app,
req: request(method, path),
}
}
pub fn get<'a>(&'a self, path: &str) -> Call<'a> {
self.call(Method::GET, path)
}
pub fn post<'a>(&'a self, path: &str) -> Call<'a> {
self.call(Method::POST, path)
}
pub fn put<'a>(&'a self, path: &str) -> Call<'a> {
self.call(Method::PUT, path)
}
pub fn patch<'a>(&'a self, path: &str) -> Call<'a> {
self.call(Method::PATCH, path)
}
pub fn delete<'a>(&'a self, path: &str) -> Call<'a> {
self.call(Method::DELETE, path)
}
}
pub struct Call<'a> {
app: &'a App,
req: Request<Body>,
}
impl<'a> Call<'a> {
pub fn body<B: Into<Body>>(mut self, body: B) -> Self {
*self.req.body_mut() = body.into();
self
}
pub fn body_json<T: Serialize>(mut self, body: &T) -> Self {
*self.req.body_mut() = serde_json::to_vec(body).unwrap().into();
self
}
pub async fn dispatch_body(self) -> Response<Body> {
self.app.dispatch(self.req, LOCAL.into()).await
}
pub async fn dispatch_bytes(self) -> Response<Bytes> {
let (parts, body) = self.dispatch_body().await.into_parts();
let bytes = to_bytes(body).await.unwrap();
Response::from_parts(parts, bytes)
}
pub async fn dispatch(self) -> Response<String> {
self.dispatch_bytes()
.await
.map(|b| String::from_utf8_lossy(&*b).into_owned())
}
pub async fn dispatch_json<T: DeserializeOwned>(self) -> Response<T> {
self.dispatch_bytes()
.await
.map(|b| serde_json::from_slice(&*b).unwrap())
}
}