Skip to content

Commit 8867b9e

Browse files
committed
move all the reqwest related code to a different file
1 parent b58c067 commit 8867b9e

File tree

8 files changed

+131
-114
lines changed

8 files changed

+131
-114
lines changed

examples/cli-app-with-reqwest/Cargo.toml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,4 +14,5 @@ serde_json = "1.0"
1414
lazy_static = "1.4.0"
1515
reqwest = "0.11.16"
1616
async-trait = "0.1.51"
17-
tokio = { version = "1.27.0", features = ["full"] }
17+
tokio = { version = "1.27.0", features = ["full"] }
18+
yaup = "0.2.0"

examples/cli-app-with-reqwest/src/main.rs

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
11
use async_trait::async_trait;
22
use lazy_static::lazy_static;
33
use meilisearch_sdk::errors::Error;
4-
use meilisearch_sdk::request::{
5-
add_query_parameters, parse_response, qualified_version, HttpClient, Method,
6-
};
4+
use meilisearch_sdk::request::{parse_response, qualified_version, HttpClient, Method};
75
use meilisearch_sdk::{client::*, settings::Settings};
86
use serde::de::DeserializeOwned;
97
use serde::{Deserialize, Serialize};
@@ -19,7 +17,7 @@ lazy_static! {
1917
#[derive(Debug, Clone, Serialize)]
2018
pub struct ReqwestClient;
2119

22-
#[async_trait(?Send)]
20+
#[async_trait]
2321
impl HttpClient for ReqwestClient {
2422
async fn request<Query, Body, Output>(
2523
&self,
@@ -249,3 +247,13 @@ impl fmt::Display for ClothesDisplay {
249247
)
250248
}
251249
}
250+
251+
fn add_query_parameters<Query: Serialize>(url: &str, query: &Query) -> Result<String, Error> {
252+
let query = yaup::to_string(query)?;
253+
254+
if query.is_empty() {
255+
Ok(url.to_string())
256+
} else {
257+
Ok(format!("{url}?{query}"))
258+
}
259+
}

examples/cli-app/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,3 +12,4 @@ futures = "0.3"
1212
serde = { version="1.0", features = ["derive"] }
1313
serde_json = "1.0"
1414
lazy_static = "1.4.0"
15+
yaup = "0.2.0"

meilisearch-index-setting-macro/src/lib.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ fn get_index_config_implementation(
128128

129129
quote! {
130130
#[::meilisearch_sdk::macro_helper::async_trait(?Send)]
131-
impl ::meilisearch_sdk::documents::IndexConfig<::meilisearch_sdk::request::ReqwestClient> for #struct_ident {
131+
impl ::meilisearch_sdk::documents::IndexConfig<::meilisearch_sdk::reqwest::ReqwestClient> for #struct_ident {
132132
const INDEX_STR: &'static str = #index_name;
133133

134134
fn generate_settings() -> ::meilisearch_sdk::settings::Settings {
@@ -140,7 +140,7 @@ fn get_index_config_implementation(
140140
#distinct_attr_token
141141
}
142142

143-
async fn generate_index(client: &::meilisearch_sdk::client::Client<::meilisearch_sdk::request::ReqwestClient>) -> std::result::Result<::meilisearch_sdk::indexes::Index<::meilisearch_sdk::request::ReqwestClient>, ::meilisearch_sdk::tasks::Task> {
143+
async fn generate_index(client: &::meilisearch_sdk::client::Client<::meilisearch_sdk::reqwest::ReqwestClient>) -> std::result::Result<::meilisearch_sdk::indexes::Index<::meilisearch_sdk::reqwest::ReqwestClient>, ::meilisearch_sdk::tasks::Task> {
144144
return client.create_index(#index_name, #primary_key_token)
145145
.await.unwrap()
146146
.wait_for_completion(&client, ::std::option::Option::None, ::std::option::Option::None)

src/client.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ impl Client {
4848
/// ```
4949
pub fn new(host: impl Into<String>, api_key: Option<impl Into<String>>) -> Client {
5050
let api_key = api_key.map(|key| key.into());
51-
let http_client = ReqwestClient::new(api_key.as_deref());
51+
let http_client = crate::reqwest::ReqwestClient::new(api_key.as_deref());
5252

5353
Client {
5454
host: host.into(),
@@ -1142,7 +1142,7 @@ mod tests {
11421142

11431143
use meilisearch_test_macro::meilisearch_test;
11441144

1145-
use crate::{client::*, key::Action};
1145+
use crate::{client::*, key::Action, reqwest::qualified_version};
11461146

11471147
#[derive(Debug, Serialize, Deserialize, PartialEq)]
11481148
struct Document {

src/lib.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,10 @@ mod tenant_tokens;
255255
mod utils;
256256

257257
#[cfg(feature = "reqwest")]
258-
pub type DefaultHttpClient = request::ReqwestClient;
258+
pub mod reqwest;
259+
260+
#[cfg(feature = "reqwest")]
261+
pub type DefaultHttpClient = reqwest::ReqwestClient;
259262

260263
#[cfg(not(feature = "reqwest"))]
261264
pub type DefaultHttpClient = std::convert::Infallible;

src/request.rs

Lines changed: 2 additions & 104 deletions
Original file line numberDiff line numberDiff line change
@@ -63,20 +63,9 @@ impl<Q, B> Method<Q, B> {
6363
Method::Patch { body, query: _ } => Some(body),
6464
}
6565
}
66-
67-
#[cfg(feature = "reqwest")]
68-
pub fn verb(&self) -> reqwest::Method {
69-
match self {
70-
Method::Get { .. } => reqwest::Method::GET,
71-
Method::Delete { .. } => reqwest::Method::DELETE,
72-
Method::Post { .. } => reqwest::Method::POST,
73-
Method::Put { .. } => reqwest::Method::PUT,
74-
Method::Patch { .. } => reqwest::Method::PATCH,
75-
}
76-
}
7766
}
7867

79-
#[async_trait(?Send)]
68+
#[async_trait]
8069
pub trait HttpClient: Clone + Send + Sync {
8170
async fn request<Query, Body, Output>(
8271
&self,
@@ -113,91 +102,6 @@ pub trait HttpClient: Clone + Send + Sync {
113102
) -> Result<Output, Error>;
114103
}
115104

116-
#[cfg(feature = "reqwest")]
117-
#[derive(Debug, Clone, Default)]
118-
pub struct ReqwestClient {
119-
client: reqwest::Client,
120-
}
121-
122-
#[cfg(feature = "reqwest")]
123-
impl ReqwestClient {
124-
pub fn new(api_key: Option<&str>) -> Self {
125-
use reqwest::{header, ClientBuilder};
126-
127-
let builder = ClientBuilder::new();
128-
let mut headers = header::HeaderMap::new();
129-
headers.insert(
130-
header::USER_AGENT,
131-
header::HeaderValue::from_str(&qualified_version()).unwrap(),
132-
);
133-
134-
if let Some(api_key) = api_key {
135-
headers.insert(
136-
header::AUTHORIZATION,
137-
header::HeaderValue::from_str(&format!("Bearer {api_key}")).unwrap(),
138-
);
139-
}
140-
141-
let builder = builder.default_headers(headers);
142-
let client = builder.build().unwrap();
143-
144-
ReqwestClient { client }
145-
}
146-
}
147-
148-
#[cfg(feature = "reqwest")]
149-
#[async_trait(?Send)]
150-
impl HttpClient for ReqwestClient {
151-
async fn stream_request<
152-
'a,
153-
Query: Serialize + Send + Sync,
154-
Body: futures_io::AsyncRead + Send + Sync + 'static,
155-
Output: DeserializeOwned + 'static,
156-
>(
157-
&self,
158-
url: &str,
159-
method: Method<Query, Body>,
160-
content_type: &str,
161-
expected_status_code: u16,
162-
) -> Result<Output, Error> {
163-
use reqwest::header;
164-
165-
let url = add_query_parameters(url, method.query())?;
166-
167-
let mut request = self.client.request(method.verb(), &url);
168-
169-
if let Some(body) = method.into_body() {
170-
let reader = tokio_util::compat::FuturesAsyncReadCompatExt::compat(body);
171-
let stream = tokio_util::io::ReaderStream::new(reader);
172-
let body = reqwest::Body::wrap_stream(stream);
173-
174-
request = request
175-
.header(header::CONTENT_TYPE, content_type)
176-
.body(body);
177-
}
178-
179-
let response = self.client.execute(request.build()?).await?;
180-
let status = response.status().as_u16();
181-
let mut body = response.text().await?;
182-
183-
if body.is_empty() {
184-
body = "null".to_string();
185-
}
186-
187-
parse_response(status, expected_status_code, &body, url.to_string())
188-
}
189-
}
190-
191-
pub fn add_query_parameters<Query: Serialize>(url: &str, query: &Query) -> Result<String, Error> {
192-
let query = yaup::to_string(query)?;
193-
194-
if query.is_empty() {
195-
Ok(url.to_string())
196-
} else {
197-
Ok(format!("{url}?{query}"))
198-
}
199-
}
200-
201105
pub fn parse_response<Output: DeserializeOwned>(
202106
status_code: u16,
203107
expected_status_code: u16,
@@ -239,13 +143,7 @@ pub fn parse_response<Output: DeserializeOwned>(
239143
}
240144
}
241145

242-
pub fn qualified_version() -> String {
243-
const VERSION: Option<&str> = option_env!("CARGO_PKG_VERSION");
244-
245-
format!("Meilisearch Rust (v{})", VERSION.unwrap_or("unknown"))
246-
}
247-
248-
#[async_trait(?Send)]
146+
#[async_trait]
249147
impl HttpClient for Infallible {
250148
async fn request<Query, Body, Output>(
251149
&self,

src/reqwest.rs

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
use async_trait::async_trait;
2+
use serde::{de::DeserializeOwned, Serialize};
3+
4+
use crate::{
5+
errors::Error,
6+
request::{parse_response, HttpClient, Method},
7+
};
8+
9+
#[derive(Debug, Clone, Default)]
10+
pub struct ReqwestClient {
11+
client: reqwest::Client,
12+
}
13+
14+
#[cfg(feature = "reqwest")]
15+
impl ReqwestClient {
16+
pub fn new(api_key: Option<&str>) -> Self {
17+
use reqwest::{header, ClientBuilder};
18+
19+
let builder = ClientBuilder::new();
20+
let mut headers = header::HeaderMap::new();
21+
headers.insert(
22+
header::USER_AGENT,
23+
header::HeaderValue::from_str(&qualified_version()).unwrap(),
24+
);
25+
26+
if let Some(api_key) = api_key {
27+
headers.insert(
28+
header::AUTHORIZATION,
29+
header::HeaderValue::from_str(&format!("Bearer {api_key}")).unwrap(),
30+
);
31+
}
32+
33+
let builder = builder.default_headers(headers);
34+
let client = builder.build().unwrap();
35+
36+
ReqwestClient { client }
37+
}
38+
}
39+
40+
#[async_trait]
41+
impl HttpClient for ReqwestClient {
42+
async fn stream_request<
43+
'a,
44+
Query: Serialize + Send + Sync,
45+
Body: futures_io::AsyncRead + Send + Sync + 'static,
46+
Output: DeserializeOwned + 'static,
47+
>(
48+
&self,
49+
url: &str,
50+
method: Method<Query, Body>,
51+
content_type: &str,
52+
expected_status_code: u16,
53+
) -> Result<Output, Error> {
54+
use reqwest::header;
55+
56+
let url = add_query_parameters(url, method.query())?;
57+
58+
let mut request = self.client.request(verb(&method), &url);
59+
60+
if let Some(body) = method.into_body() {
61+
let reader = tokio_util::compat::FuturesAsyncReadCompatExt::compat(body);
62+
let stream = tokio_util::io::ReaderStream::new(reader);
63+
let body = reqwest::Body::wrap_stream(stream);
64+
65+
request = request
66+
.header(header::CONTENT_TYPE, content_type)
67+
.body(body);
68+
}
69+
70+
let response = self.client.execute(request.build()?).await?;
71+
let status = response.status().as_u16();
72+
let mut body = response.text().await?;
73+
74+
if body.is_empty() {
75+
body = "null".to_string();
76+
}
77+
78+
parse_response(status, expected_status_code, &body, url.to_string())
79+
}
80+
}
81+
82+
fn verb<Q, B>(method: &Method<Q, B>) -> reqwest::Method {
83+
match method {
84+
Method::Get { .. } => reqwest::Method::GET,
85+
Method::Delete { .. } => reqwest::Method::DELETE,
86+
Method::Post { .. } => reqwest::Method::POST,
87+
Method::Put { .. } => reqwest::Method::PUT,
88+
Method::Patch { .. } => reqwest::Method::PATCH,
89+
}
90+
}
91+
92+
pub fn add_query_parameters<Query: Serialize>(url: &str, query: &Query) -> Result<String, Error> {
93+
let query = yaup::to_string(query)?;
94+
95+
if query.is_empty() {
96+
Ok(url.to_string())
97+
} else {
98+
Ok(format!("{url}?{query}"))
99+
}
100+
}
101+
102+
pub fn qualified_version() -> String {
103+
const VERSION: Option<&str> = option_env!("CARGO_PKG_VERSION");
104+
105+
format!("Meilisearch Rust (v{})", VERSION.unwrap_or("unknown"))
106+
}

0 commit comments

Comments
 (0)