diff options
author | Matthias Beyer <mail@beyermatthias.de> | 2021-04-07 17:10:24 +0200 |
---|---|---|
committer | Matthias Beyer <mail@beyermatthias.de> | 2021-04-07 17:10:24 +0200 |
commit | e880f99e773512215cc9f695eb2d865af5734d90 (patch) | |
tree | 903492b8e8605f03084cb9f992f75cb39b2dfccf | |
parent | b06c02805b594babd4057817b7645253f8366539 (diff) |
Implement API request sending and response parsing
Signed-off-by: Matthias Beyer <mail@beyermatthias.de>
-rw-r--r-- | librepology/src/v1/api.rs | 45 | ||||
-rw-r--r-- | librepology/src/v1/error.rs | 3 |
2 files changed, 43 insertions, 5 deletions
diff --git a/librepology/src/v1/api.rs b/librepology/src/v1/api.rs index 4ef0d12..eb843d6 100644 --- a/librepology/src/v1/api.rs +++ b/librepology/src/v1/api.rs @@ -1,15 +1,28 @@ use crate::endpoint::EndpointUrl; -use reqwest::Client; +use crate::v1::error::Result; +use crate::v1::error::RepologyError; + +static APP_USER_AGENT: &str = concat!( + env!("CARGO_PKG_NAME"), + "/", + env!("CARGO_PKG_VERSION"), +); pub struct ApiClient { endpoint_url: &'static str, + client: reqwest::Client, } impl ApiClient { - pub fn new<EP: EndpointUrl>() -> Self { - ApiClient { - endpoint_url: EP::endpoint_url(), - } + pub fn new<EP: EndpointUrl>(timeout: std::time::Duration) -> Result<Self> { + reqwest::Client::builder() + .user_agent(APP_USER_AGENT) + .build() + .map_err(RepologyError::from) + .map(|client| ApiClient { + endpoint_url: EP::endpoint_url(), + client, + }) } pub fn projects<'a>(&'a self) -> ProjectRequestBuilder<'a> { @@ -52,6 +65,28 @@ pub struct Request<'a> { request_string: String } +impl<'a> Request<'a> { + pub async fn perform(self) -> Result<Response> { + self.client + .client + .get(format!("{}{}", self.client.endpoint_url, self.request_string)) + .send() + .await? + .text() + .await + .map(Response) + .map_err(RepologyError::from) + } +} + +pub struct Response(String); + +impl Response { + pub fn deserialize<'de, T: serde::Deserialize<'de>>(&'de self) -> Result<T> { + serde_json::from_str(&self.0).map_err(RepologyError::from) + } +} + pub struct ProjectRequestBuilderWithName<'a>(&'a ApiClient, String); impl<'a> ToRequest<'a> for ProjectRequestBuilderWithName<'a> { diff --git a/librepology/src/v1/error.rs b/librepology/src/v1/error.rs index cbc66c7..67b924f 100644 --- a/librepology/src/v1/error.rs +++ b/librepology/src/v1/error.rs @@ -8,6 +8,9 @@ pub enum RepologyError { #[error("serde_json error")] SerdeJsonError(#[from] serde_json::Error), + #[error("Request error")] + ReqwestError(#[from] reqwest::Error), + #[error("IO error")] IoError(#[from] std::io::Error), |