use crate::errors::NetworkError; use bytes::Bytes; use protobuf::Message; use reqwest::{Client, Response}; use std::{convert::TryFrom, time::Duration}; pub struct FlowyRequest { client: Client, } impl FlowyRequest { pub fn new() -> Self { let client = default_client(); Self { client } } pub async fn get(&self, url: &str) -> Result where T: Message, { let url = url.to_owned(); let response = self.client.get(&url).send().await?; parse_response(response).await } pub async fn post(&self, url: &str, data: T) -> Result where T: Message, { let url = url.to_owned(); let body = data.write_to_bytes()?; let response = self.client.post(&url).body(body).send().await?; parse_response(response).await } pub async fn post_data(&self, url: &str, bytes: Vec) -> Result where T: for<'a> TryFrom<&'a Vec>, { let url = url.to_owned(); let response = self.client.post(&url).body(bytes).send().await?; let bytes = response.bytes().await?.to_vec(); let data = T::try_from(&bytes).map_err(|_e| panic!("")).unwrap(); Ok(data) } } async fn parse_response(response: Response) -> Result where T: Message, { let bytes = response.bytes().await?; parse_bytes(bytes) } fn parse_bytes(bytes: Bytes) -> Result where T: Message, { match Message::parse_from_bytes(&bytes) { Ok(data) => Ok(data), Err(e) => { log::error!( "Parse bytes for {:?} failed: {}", std::any::type_name::(), e ); Err(e.into()) }, } } 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() }, } }