Simplify 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,7 +42,8 @@ pub async fn request_multipart<T: DeserializeOwned>(
method_name: &str,
params: Option<Form>,
) -> ResponseResult<T> {
- let mut response = client
+ process_response(
+ client
.post(&method_url(TELEGRAM_API_URL, token, method_name))
.apply(|request_builder| match params {
Some(params) => request_builder.multipart(params),
@@ -50,25 +51,9 @@ pub async fn request_multipart<T: DeserializeOwned>(
})
.send()
.await
- .map_err(RequestError::NetworkError)?;
-
- let response = serde_json::from_str::<TelegramResponse<T>>(
- &response.text().await.map_err(RequestError::NetworkError)?,
+ .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<T: DeserializeOwned, P: Serialize>(
@@ -77,13 +62,20 @@ pub async fn request_json<T: DeserializeOwned, P: Serialize>(
method_name: &str,
params: &P,
) -> ResponseResult<T> {
- let mut response = client
+ process_response(
+ client
.post(&method_url(TELEGRAM_API_URL, token, method_name))
.json(params)
.send()
.await
- .map_err(RequestError::NetworkError)?;
+ .map_err(RequestError::NetworkError)?,
+ )
+ .await
+}
+async fn process_response<T: DeserializeOwned>(
+ mut response: Response,
+) -> ResponseResult<T> {
let response = serde_json::from_str::<TelegramResponse<T>>(
&response.text().await.map_err(RequestError::NetworkError)?,
)
@@ -107,14 +99,14 @@ pub async fn request_json<T: DeserializeOwned, P: Serialize>(
#[serde(untagged)]
enum TelegramResponse<R> {
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
