Skip to content

Commit

Permalink
Expose request builder, v0.3.3
Browse files Browse the repository at this point in the history
  • Loading branch information
ljoonal committed Mar 3, 2023
1 parent c5a6d78 commit f00b697
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 27 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "racal"
version = "0.3.2"
version = "0.3.3"
edition = "2021"
license = "MPL-2.0"
authors = ["ljoonal"]
Expand Down
54 changes: 28 additions & 26 deletions src/reqwest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,31 +26,6 @@ impl From<reqwest::Error> for ApiError {
fn from(err: reqwest::Error) -> Self { Self::Reqwest(err) }
}

fn build_request<ReturnType, ApiState, QueryableType>(
http: &Client, api_state: &ApiState, queryable: &QueryableType,
) -> Result<RequestBuilder, ApiError>
where
ReturnType: DeserializeOwned,
QueryableType: Queryable<ApiState, ReturnType> + Send + Sync,
{
let mut request = http.request(
match queryable.method(api_state) {
RequestMethod::Get => reqwest::Method::GET,
RequestMethod::Head => reqwest::Method::HEAD,
RequestMethod::Patch => reqwest::Method::PATCH,
RequestMethod::Post => reqwest::Method::POST,
RequestMethod::Put => reqwest::Method::PUT,
RequestMethod::Delete => reqwest::Method::DELETE,
},
queryable.url(api_state),
);
if let Some(body) = queryable.body(api_state) {
request = request.body(body?);
}

Ok(request)
}

/// An API client that can be used to create queries
#[async_trait::async_trait]
pub trait ApiClient<State> {
Expand Down Expand Up @@ -99,7 +74,7 @@ pub trait ApiClient<State> {
FromState: FromApiState<State>,
QueryableType: Queryable<FromState, ReturnType> + Send + Sync,
{
let request = build_request::<ReturnType, FromState, QueryableType>(
let request = Self::build_request(
self.client(),
FromState::from_state(self.state()),
&queryable,
Expand All @@ -109,4 +84,31 @@ pub trait ApiClient<State> {

self.handle_response(queryable, response).await
}

/// Builds the base request
fn build_request<ReturnType, FromState, QueryableType>(
http: &Client, api_state: &FromState, queryable: &QueryableType,
) -> Result<RequestBuilder, ApiError>
where
ReturnType: DeserializeOwned,
FromState: FromApiState<State>,
QueryableType: Queryable<FromState, ReturnType> + Send + Sync,
{
let mut request = http.request(
match queryable.method(api_state) {
RequestMethod::Get => reqwest::Method::GET,
RequestMethod::Head => reqwest::Method::HEAD,
RequestMethod::Patch => reqwest::Method::PATCH,
RequestMethod::Post => reqwest::Method::POST,
RequestMethod::Put => reqwest::Method::PUT,
RequestMethod::Delete => reqwest::Method::DELETE,
},
queryable.url(api_state),
);
if let Some(body) = queryable.body(api_state) {
request = request.body(body?);
}

Ok(request)
}
}

0 comments on commit f00b697

Please sign in to comment.