Skip to content

Commit 9a4ee80

Browse files
committed
update the cli-app-with-reqwest to work with awc
1 parent 741bf4e commit 9a4ee80

File tree

3 files changed

+86
-84
lines changed

3 files changed

+86
-84
lines changed

examples/cli-app-with-reqwest/Cargo.toml renamed to examples/cli-app-with-awc/Cargo.toml

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
[package]
2-
name = "cli-app-with-reqwest"
2+
name = "cli-app-with-awc"
33
version = "0.0.0"
44
edition = "2021"
55
publish = false
@@ -12,7 +12,9 @@ futures = "0.3"
1212
serde = { version = "1.0", features = ["derive"] }
1313
serde_json = "1.0"
1414
lazy_static = "1.4.0"
15-
reqwest = "0.11.16"
15+
awc = "3.4"
1616
async-trait = "0.1.51"
1717
tokio = { version = "1.27.0", features = ["full"] }
1818
yaup = "0.2.0"
19+
tokio-util = { version = "0.7.10", features = ["full"] }
20+
actix-rt = "2.9.0"

examples/cli-app-with-reqwest/src/main.rs renamed to examples/cli-app-with-awc/src/main.rs

Lines changed: 82 additions & 82 deletions
Original file line numberDiff line numberDiff line change
@@ -1,107 +1,97 @@
11
use async_trait::async_trait;
2-
use lazy_static::lazy_static;
32
use meilisearch_sdk::errors::Error;
43
use meilisearch_sdk::request::{parse_response, HttpClient, Method};
54
use meilisearch_sdk::{client::*, settings::Settings};
65
use serde::de::DeserializeOwned;
76
use serde::{Deserialize, Serialize};
8-
use serde_json::to_string;
97
use std::fmt;
108
use std::io::stdin;
119

12-
lazy_static! {
13-
static ref CLIENT: Client<ReqwestClient> =
14-
Client::new_with_client("http://localhost:7700", Some("masterKey"), ReqwestClient);
10+
#[derive(Debug, Clone)]
11+
pub struct AwcClient {
12+
api_key: Option<String>,
1513
}
1614

17-
#[derive(Debug, Clone, Serialize)]
18-
pub struct ReqwestClient;
15+
impl AwcClient {
16+
pub fn new(api_key: Option<&str>) -> Result<Self, Error> {
17+
Ok(AwcClient {
18+
api_key: api_key.map(|key| key.to_string()),
19+
})
20+
}
21+
}
1922

2023
#[async_trait(?Send)]
21-
impl HttpClient for ReqwestClient {
22-
async fn request<Query, Body, Output>(
24+
impl HttpClient for AwcClient {
25+
async fn stream_request<
26+
Query: Serialize + Send + Sync,
27+
Body: futures::AsyncRead + Send + Sync + 'static,
28+
Output: DeserializeOwned + 'static,
29+
>(
2330
&self,
2431
url: &str,
2532
method: Method<Query, Body>,
33+
content_type: &str,
2634
expected_status_code: u16,
27-
) -> Result<Output, Error>
28-
where
29-
Query: Serialize + Send + Sync,
30-
Body: Serialize + Send + Sync,
31-
Output: DeserializeOwned + 'static + Send,
32-
{
33-
let response = match &method {
34-
Method::Get { query } => {
35-
let url = add_query_parameters(url, query)?;
36-
let client = reqwest::Client::new();
37-
let builder = client.request(reqwest::Method::GET, url.as_str());
38-
let req = builder.build().unwrap();
39-
client.execute(req).await.unwrap()
40-
}
41-
Method::Post { query, body } => {
42-
let url = add_query_parameters(url, query)?;
43-
let client = reqwest::Client::new();
44-
let mut builder = client.request(reqwest::Method::POST, url.as_str());
45-
builder = builder.header(reqwest::header::CONTENT_TYPE, "application/json");
46-
let req = builder.body(to_string(body).unwrap()).build().unwrap();
47-
client.execute(req).await.unwrap()
48-
}
49-
Method::Patch { query, body } => {
50-
let url = add_query_parameters(url, query)?;
51-
let client = reqwest::Client::new();
52-
let mut builder = client.request(reqwest::Method::PATCH, url.as_str());
53-
builder = builder.header(reqwest::header::CONTENT_TYPE, "application/json");
54-
let req = builder.body(to_string(body).unwrap()).build().unwrap();
55-
client.execute(req).await.unwrap()
56-
}
57-
Method::Put { query, body } => {
58-
let url = add_query_parameters(url, query)?;
59-
let client = reqwest::Client::new();
60-
let mut builder = client.request(reqwest::Method::PUT, url.as_str());
61-
builder = builder.header(reqwest::header::CONTENT_TYPE, "application/json");
62-
let req = builder.body(to_string(body).unwrap()).build().unwrap();
63-
client.execute(req).await.unwrap()
64-
}
65-
Method::Delete { query } => {
66-
let url = add_query_parameters(url, query)?;
67-
let client = reqwest::Client::new();
68-
let mut builder = client.request(reqwest::Method::DELETE, url.as_str());
69-
builder = builder.header(reqwest::header::CONTENT_TYPE, "application/json");
70-
let req = builder.build().unwrap();
71-
client.execute(req).await.unwrap()
72-
}
35+
) -> Result<Output, Error> {
36+
let mut builder = awc::ClientBuilder::new();
37+
if let Some(ref api_key) = self.api_key {
38+
builder = builder.bearer_auth(api_key);
39+
}
40+
builder = builder.add_default_header(("User-Agent", "Rust client with Awc"));
41+
let client = builder.finish();
42+
43+
let query = method.query();
44+
let query = yaup::to_string(query)?;
45+
46+
let url = if query.is_empty() {
47+
url.to_string()
48+
} else {
49+
format!("{url}?{query}")
7350
};
7451

75-
let status = response.status().as_u16();
52+
let url = add_query_parameters(&url, method.query())?;
53+
let request = client.request(verb(&method), &url);
7654

77-
let mut body = response.text().await.unwrap();
55+
let mut response = if let Some(body) = method.into_body() {
56+
let reader = tokio_util::compat::FuturesAsyncReadCompatExt::compat(body);
57+
let stream = tokio_util::io::ReaderStream::new(reader);
58+
request
59+
.content_type(content_type)
60+
.send_stream(stream)
61+
.await
62+
.map_err(|err| Error::Other(Box::new(err)))?
63+
} else {
64+
request
65+
.send()
66+
.await
67+
.map_err(|err| Error::Other(Box::new(err)))?
68+
};
69+
70+
let status = response.status().as_u16();
71+
let mut body = String::from_utf8(
72+
response
73+
.body()
74+
.await
75+
.map_err(|err| Error::Other(Box::new(err)))?
76+
.to_vec(),
77+
)
78+
.map_err(|err| Error::Other(Box::new(err)))?;
7879

7980
if body.is_empty() {
8081
body = "null".to_string();
8182
}
8283

8384
parse_response(status, expected_status_code, &body, url.to_string())
8485
}
85-
86-
async fn stream_request<
87-
Query: Serialize + Send + Sync,
88-
Body: futures::AsyncRead + Send + Sync + 'static,
89-
Output: DeserializeOwned + 'static,
90-
>(
91-
&self,
92-
_url: &str,
93-
_method: Method<Query, Body>,
94-
_content_type: &str,
95-
_expected_status_code: u16,
96-
) -> Result<Output, Error> {
97-
unimplemented!("stream_request is not implemented for ReqwestClient")
98-
}
9986
}
10087

101-
#[tokio::main]
88+
#[actix_rt::main]
10289
async fn main() {
90+
let http_client = AwcClient::new(Some("masterKey")).unwrap();
91+
let client = Client::new_with_client("http://localhost:7700", Some("masterKey"), http_client);
92+
10393
// build the index
104-
build_index().await;
94+
build_index(&client).await;
10595

10696
// enter in search queries or quit
10797
loop {
@@ -116,18 +106,18 @@ async fn main() {
116106
break;
117107
}
118108
_ => {
119-
search(input_string.trim()).await;
109+
search(&client, input_string.trim()).await;
120110
}
121111
}
122112
}
123113
// get rid of the index at the end, doing this only so users don't have the index without knowing
124-
let _ = CLIENT.delete_index("clothes").await.unwrap();
114+
let _ = client.delete_index("clothes").await.unwrap();
125115
}
126116

127-
async fn search(query: &str) {
117+
async fn search(client: &Client<AwcClient>, query: &str) {
128118
// make the search query, which excutes and serializes hits into the
129119
// ClothesDisplay struct
130-
let query_results = CLIENT
120+
let query_results = client
131121
.index("clothes")
132122
.search()
133123
.with_query(query)
@@ -147,7 +137,7 @@ async fn search(query: &str) {
147137
}
148138
}
149139

150-
async fn build_index() {
140+
async fn build_index(client: &Client<AwcClient>) {
151141
// reading and parsing the file
152142
let content = include_str!("../assets/clothes.json");
153143

@@ -177,12 +167,12 @@ async fn build_index() {
177167
.with_synonyms(synonyms);
178168

179169
//add the settings to the index
180-
let result = CLIENT
170+
let result = client
181171
.index("clothes")
182172
.set_settings(&settings)
183173
.await
184174
.unwrap()
185-
.wait_for_completion(&CLIENT, None, None)
175+
.wait_for_completion(client, None, None)
186176
.await
187177
.unwrap();
188178

@@ -194,12 +184,12 @@ async fn build_index() {
194184
}
195185

196186
// add the documents
197-
let result = CLIENT
187+
let result = client
198188
.index("clothes")
199189
.add_or_update(&clothes, Some("id"))
200190
.await
201191
.unwrap()
202-
.wait_for_completion(&CLIENT, None, None)
192+
.wait_for_completion(client, None, None)
203193
.await
204194
.unwrap();
205195

@@ -255,3 +245,13 @@ fn add_query_parameters<Query: Serialize>(url: &str, query: &Query) -> Result<St
255245
Ok(format!("{url}?{query}"))
256246
}
257247
}
248+
249+
fn verb<Q, B>(method: &Method<Q, B>) -> awc::http::Method {
250+
match method {
251+
Method::Get { .. } => awc::http::Method::GET,
252+
Method::Delete { .. } => awc::http::Method::DELETE,
253+
Method::Post { .. } => awc::http::Method::POST,
254+
Method::Put { .. } => awc::http::Method::PUT,
255+
Method::Patch { .. } => awc::http::Method::PATCH,
256+
}
257+
}

0 commit comments

Comments
 (0)