From cb5ea4a5b79e1336af1b948ae08b8e1c53c6693d Mon Sep 17 00:00:00 2001 From: Temirkhan Myrzamadi Date: Fri, 20 Sep 2019 06:24:08 +0600 Subject: [PATCH] Simplify src/core/network/mod.rs --- src/core/network/mod.rs | 62 ++++++++++++++++++----------------------- 1 file changed, 27 insertions(+), 35 deletions(-) diff --git a/src/core/network/mod.rs b/src/core/network/mod.rs index 244c6d63..83a3e166 100644 --- a/src/core/network/mod.rs +++ b/src/core/network/mod.rs @@ -5,7 +5,7 @@ use crate::core::{ use apply::Apply; use reqwest::{ - r#async::{multipart::Form, Client}, + r#async::{multipart::Form, Client, Response}, StatusCode, }; use serde::{de::DeserializeOwned, Serialize}; @@ -42,33 +42,18 @@ pub async fn request_multipart( method_name: &str, params: Option
, ) -> ResponseResult { - let mut response = client - .post(&method_url(TELEGRAM_API_URL, token, method_name)) - .apply(|request_builder| match params { - Some(params) => request_builder.multipart(params), - None => request_builder, - }) - .send() - .await - .map_err(RequestError::NetworkError)?; - - let response = serde_json::from_str::>( - &response.text().await.map_err(RequestError::NetworkError)?, + process_response( + client + .post(&method_url(TELEGRAM_API_URL, token, method_name)) + .apply(|request_builder| match params { + Some(params) => request_builder.multipart(params), + None => request_builder, + }) + .send() + .await + .map_err(RequestError::NetworkError)?, ) - .map_err(RequestError::InvalidJson)?; - - match response { - TelegramResponse::Ok { result, .. } => Ok(result), - TelegramResponse::Err { - description, - error_code, - response_parameters: _, - .. - } => Err(RequestError::ApiError { - description, - status_code: StatusCode::from_u16(error_code).unwrap(), - }), - } + .await } pub async fn request_json( @@ -77,13 +62,20 @@ pub async fn request_json( method_name: &str, params: &P, ) -> ResponseResult { - let mut response = client - .post(&method_url(TELEGRAM_API_URL, token, method_name)) - .json(params) - .send() - .await - .map_err(RequestError::NetworkError)?; + process_response( + client + .post(&method_url(TELEGRAM_API_URL, token, method_name)) + .json(params) + .send() + .await + .map_err(RequestError::NetworkError)?, + ) + .await +} +async fn process_response( + mut response: Response, +) -> ResponseResult { let response = serde_json::from_str::>( &response.text().await.map_err(RequestError::NetworkError)?, ) @@ -107,14 +99,14 @@ pub async fn request_json( #[serde(untagged)] enum TelegramResponse { Ok { - /// Dummy field. Used for deserialization. + /// A dummy field. Used only for deserialization. #[allow(dead_code)] ok: bool, // TODO: True type result: R, }, Err { - /// Dummy field. Used for deserialization. + /// A dummy field. Used only for deserialization. #[allow(dead_code)] ok: bool, // TODO: False type