Simplify src/core/network/mod.rs

This commit is contained in:
Temirkhan Myrzamadi 2019-09-20 06:24:08 +06:00
parent cc9d59cf49
commit cb5ea4a5b7

View file

@ -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<T: DeserializeOwned>(
method_name: &str,
params: Option<Form>,
) -> ResponseResult<T> {
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::<TelegramResponse<T>>(
&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<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
.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<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