AppFlowy/rust-lib/flowy-net/src/request/request.rs

155 lines
4.1 KiB
Rust
Raw Normal View History

2021-08-23 00:27:29 +00:00
use crate::{
2021-08-23 15:02:42 +00:00
errors::{ErrorCode, ServerError},
2021-08-23 00:27:29 +00:00
response::FlowyResponse,
};
2021-08-20 13:09:21 +00:00
use bytes::Bytes;
use hyper::http;
2021-08-23 00:27:29 +00:00
use protobuf::ProtobufError;
use reqwest::{Client, Method, Response};
use std::{
convert::{TryFrom, TryInto},
time::Duration,
};
use tokio::sync::oneshot;
2021-08-20 13:09:21 +00:00
2021-08-23 00:27:29 +00:00
pub struct HttpRequestBuilder {
url: String,
body: Option<Bytes>,
2021-08-25 09:34:20 +00:00
response: Option<Response>,
2021-08-23 00:27:29 +00:00
method: Method,
}
impl HttpRequestBuilder {
2021-08-23 10:39:10 +00:00
fn new(url: &str) -> Self {
2021-08-23 00:27:29 +00:00
Self {
2021-08-23 10:39:10 +00:00
url: url.to_owned(),
2021-08-23 00:27:29 +00:00
body: None,
response: None,
method: Method::GET,
}
}
pub fn get(url: &str) -> Self {
2021-08-23 10:39:10 +00:00
let mut builder = Self::new(url);
2021-08-23 00:27:29 +00:00
builder.method = Method::GET;
builder
}
pub fn post(url: &str) -> Self {
2021-08-23 10:39:10 +00:00
let mut builder = Self::new(url);
2021-08-23 00:27:29 +00:00
builder.method = Method::POST;
builder
}
2021-08-25 09:34:20 +00:00
pub fn patch(url: &str) -> Self {
let mut builder = Self::new(url);
builder.method = Method::PATCH;
builder
}
pub fn delete(url: &str) -> Self {
let mut builder = Self::new(url);
builder.method = Method::DELETE;
builder
}
2021-08-23 00:27:29 +00:00
pub fn protobuf<T1>(mut self, body: T1) -> Result<Self, ServerError>
where
T1: TryInto<Bytes, Error = ProtobufError>,
{
let body: Bytes = body.try_into()?;
self.body = Some(body);
Ok(self)
}
pub async fn send(mut self) -> Result<Self, ServerError> {
let (tx, rx) = oneshot::channel::<Result<Response, _>>();
let url = self.url.clone();
let body = self.body.take();
let method = self.method.clone();
2021-08-23 10:39:10 +00:00
// reqwest client is not 'Sync' by channel is.
2021-08-23 00:27:29 +00:00
tokio::spawn(async move {
let client = default_client();
let mut builder = client.request(method, url);
if let Some(body) = body {
builder = builder.body(body);
}
let response = builder.send().await;
tx.send(response);
});
let response = rx.await??;
2021-08-25 09:34:20 +00:00
self.response = Some(response);
2021-08-23 00:27:29 +00:00
Ok(self)
}
2021-08-25 09:34:20 +00:00
pub async fn response<T2>(self) -> Result<T2, ServerError>
2021-08-23 00:27:29 +00:00
where
T2: TryFrom<Bytes, Error = ProtobufError>,
{
2021-08-25 09:34:20 +00:00
match self.response {
2021-08-23 00:27:29 +00:00
None => {
let msg = format!("Request: {} receives unexpected empty body", self.url);
2021-08-23 15:02:42 +00:00
Err(ServerError::payload_none().context(msg))
2021-08-23 00:27:29 +00:00
},
2021-08-25 09:34:20 +00:00
Some(response) => {
let data = get_response_data(response).await?;
Ok(T2::try_from(data)?)
},
2021-08-23 00:27:29 +00:00
}
}
}
#[allow(dead_code)]
2021-08-21 09:17:54 +00:00
pub async fn http_post<T1, T2>(url: &str, data: T1) -> Result<T2, ServerError>
where
T1: TryInto<Bytes, Error = ProtobufError>,
T2: TryFrom<Bytes, Error = ProtobufError>,
{
2021-08-23 00:27:29 +00:00
let body: Bytes = data.try_into()?;
2021-08-21 04:34:11 +00:00
let url = url.to_owned();
let (tx, rx) = oneshot::channel::<Result<Response, _>>();
2021-08-20 13:09:21 +00:00
2021-08-23 00:27:29 +00:00
// reqwest client is not 'Sync' by channel is.
tokio::spawn(async move {
let client = default_client();
2021-08-23 00:27:29 +00:00
let response = client.post(&url).body(body).send().await;
tx.send(response);
});
2021-08-20 13:09:21 +00:00
2021-08-21 09:17:54 +00:00
let response = rx.await??;
2021-08-22 14:16:03 +00:00
let data = get_response_data(response).await?;
Ok(T2::try_from(data)?)
2021-08-20 13:09:21 +00:00
}
2021-08-22 14:16:03 +00:00
async fn get_response_data(original: Response) -> Result<Bytes, ServerError> {
if original.status() == http::StatusCode::OK {
let bytes = original.bytes().await?;
let response: FlowyResponse = serde_json::from_slice(&bytes)?;
match response.error {
None => Ok(response.data),
Some(error) => Err(error),
}
} else {
2021-08-23 15:02:42 +00:00
Err(ServerError::http().context(original))
2021-08-20 13:09:21 +00:00
}
}
fn default_client() -> Client {
let result = reqwest::Client::builder()
.connect_timeout(Duration::from_millis(500))
.timeout(Duration::from_secs(5))
.build();
match result {
Ok(client) => client,
Err(e) => {
log::error!("Create reqwest client failed: {}", e);
reqwest::Client::new()
},
}
}