From e880f99e773512215cc9f695eb2d865af5734d90 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Wed, 7 Apr 2021 17:10:24 +0200 Subject: Implement API request sending and response parsing Signed-off-by: Matthias Beyer --- librepology/src/v1/api.rs | 45 ++++++++++++++++++++++++++++++++++++++++----- 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() -> Self { - ApiClient { - endpoint_url: EP::endpoint_url(), - } + pub fn new(timeout: std::time::Duration) -> Result { + 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 { + 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 { + 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), -- cgit v1.2.3